linux下C語言多執行緒程式設計

2021-06-27 09:29:25 字數 2062 閱讀 6499

#include #include 

#include

#include

#define max 10pthread_t thread[2];

pthread_mutex_t mut;

int number=0

, i;

void *thread1()

printf(

"thread1 :主函式在等我完成任務嗎?\n");

pthread_exit(null);

}void *thread2()

printf(

"thread2 :主函式在等我完成任務嗎?\n");

pthread_exit(null);

}void thread_create(void

)void thread_wait(void

)

if(thread[1] !=0)

}int

main()

執行結果

我是主函式哦,我正在建立執行緒,呵呵

執行緒1被建立

執行緒2被建立

我是主函式哦,我正在等待執行緒完成任務阿,呵呵

thread1 : i

'm thread 1

thread1 : number = 0

thread2 : i

'm thread 2

thread2 : number = 1

thread1 : number = 2

thread2 : number = 3

thread1 : number = 4

thread2 : number = 5

thread1 : number = 6

thread1 : number = 7

thread2 : number = 8

thread1 : number = 9

thread2 : number = 10

thread1 :主函式在等我完成任務嗎?

執行緒1已經結束

thread2 :主函式在等我完成任務嗎?

執行緒2已經結束

下面乙個稍微複雜的多執行緒

extern int pthread_join __p ((pthread_t __th, void **__thread_return));

第乙個引數為被等待的執行緒識別符號,第二個引數為乙個使用者定義的指標,它可以用來儲存被等待執行緒的返回值。這個函式是乙個執行緒阻塞的函式,呼叫它的執行緒將一直等待到被等待的執行緒結束為止,當函式返回時,被等待執行緒的資源被收回。乙個執行緒的結束有兩種途徑,一種是象我們上面的例子一樣,函式結束了,呼叫它的執行緒也就結束了;另一種方式是通過函式pthread_exit來實現。它的函式原型為:

extern void pthread_exit __p ((void *__retval)) __attribute__ ((__noreturn__));

唯一的引數是函式的返回**,只要pthread_exit中的引數retval不是null,這個值將被傳遞給 thread_return。最後要說明的是,乙個執行緒不能被多個執行緒等待,否則第乙個接收到訊號的執行緒成功返回,其餘呼叫pthread_join的執行緒則返回錯誤**esrch。

例項:

#include #include 

#include

pthread_t tid1, tid2;

void *tret;

void *thr_fn1(

void *arg)

void *thr_fn2(

void *arg)

intmain(

void)

命令:#gcc -lthread myfile11-3

.c :#./a.out

執行結果:

thread

2exiting

thread

2 exit code 3

thread

1returning

thread

1 exit code 2

多執行緒程式設計 c語言linux下

適用與linux系統 1.了解基本概念 程序 是計算機所執行的乙個任務的描述,是面向作業系統的最小單位,作業系統能執行很多程序 執行自己寫的乙份 程式,就是讓作業系統執行乙個自己程式的程序 作業系統會根據程式分配定量的資源 執行緒 面想程式 程序 的,把乙個程式分成多個執行緒可以實現並髮式,多工執行...

linux 下c語言 多執行緒程式設計

最近學習c語言和linux,記錄一下linux中線程的簡單使用 linux執行緒一般用pthread庫建立。pthread是 posix thread的簡稱。在linux的 lib目錄下,可以找到名為libpthread x.x.so x.x是版本號 的庫。下面模擬兩個執行緒 threaddemo....

linux下C語言多執行緒程式設計例項

我們通過建立兩個執行緒來實現對乙個數的遞加。或許這個例項沒有實際運用的價值,但是稍微改動一下,我們就可以用到其他地方去拉。下面是我們的 thread example.c c multiple thread programming in linux author falcon e mail tunzh...