Linux下C語言多執行緒例項

2021-06-05 19:50:07 字數 1507 閱讀 4746

建立兩個執行緒訪問互斥資料,對其加1輸出。這是乙個多執行緒最常見的例子:

#include

#include

#include

#include

#define max 10

pthread_t thread[2];

pthread_mutex_t mut;

int number=0, i;

void *thread1()

printf("thread1 :the main is waiting for me ?\n");

pthread_exit(null);}

void *thread2()

printf("thread2 :the main is waiting for me ?\n");

pthread_exit(null);}

void thread_create(void)

else

if((temp = pthread_create(&thread[1], null, thread2, null)) != 0)

else }

void thread_wait(void)

if(thread[1] !=0)}

int main()

編譯:

gcc -o example -lpthread example.c

執行:

./example

輸出結果:

i am the main thread ,i am creating thread .

thread1 : i'm thread 1

thread1 : number = 0

the thread1 create success !

thread2 : i'm thread 2

thread2 : number = 1

the thread2 create success !

i am the main thread ,i am waiting for the end of the thread.

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 :the main is waiting for me ?

the thread1 is end !

thread2 :the main is waiting for me ?

the thread2 is end !

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

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

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

學東西,往往例項才是最讓人感興趣的,老是學基礎理論,不動手,感覺沒有成就感,呵呵。下面先來乙個例項。我們通過建立兩個執行緒來實現對乙個數的遞加。或許這個例項沒有實際運用的價值,但是稍微改動一下,我們就可以用到其他地方去拉。下面是我們的 thread example.c c multiple thre...

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

學東西,往往例項才是最讓人感興趣的,老是學基礎理論,不動手,感覺沒有成就感,呵呵。下面先來乙個例項。我們通過建立兩個執行緒來實現對乙個數的遞加。或許這個例項沒有實際運用的價值,但是稍微改動一下,我們就可以用到其他地方去拉。下面是我們的 thread example.c c multiple thre...