#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <errno.h> int gnum = 0; int gsub = 100;pthread_mutex_t mutex; pthread_cond_t cond; //條件變量 void pthread_func_1 (void); void pthread_func_2 (void); int main (void) { pthread_t pt_1 = 0; pthread_t pt_2 = 0; int ret = 0; pthread_mutex_init (&mutex, NULL); //默認(rèn)情況下 互斥初始化后是解鎖狀態(tài)可用 pthread_cond_init(&cond,NULL); // //pthread_cond_init(指向pthread_cond_t的指針,屬性設(shè)置<NULL>默認(rèn)屬性) ret = pthread_create (&pt_1, NULL, (void *)pthread_func_1, NULL); if (ret != 0) printf("pthread_1_create"); ret = pthread_create (&pt_2, NULL, (void *)pthread_func_2, NULL); if (ret != 0) printf("pthread_2_create"); pthread_join (pt_1, NULL); pthread_join (pt_2, NULL); printf ("main programme exit!/n"); return 0; } void pthread_func_1 (void) { //int i = 0; printf ("pthread1 start running!\n"); while(gnum <= 100) { pthread_mutex_lock(&mutex); /*注意,這里以防線程的搶占,以造成一個線程在另一個線程sleep時多次訪問互斥資源,所以sleep要在得到互斥鎖后調(diào)用*/ sleep (1); while (gnum == 50) { printf("supend thread1!!!\n"); pthread_cond_wait(&cond, &mutex); printf("thread1 restart!!!\n"); gnum++; } gnum++; printf ("gnum=:%d\n",gnum); pthread_mutex_unlock(&mutex); /*釋放互斥鎖*/ } } void pthread_func_2 (void) { printf ("pthread2 start running!\n"); while (gsub >= 0) { pthread_mutex_lock(&mutex);//mutex被鎖住后,線程在此被掛起,等待mutex變?yōu)榻怄i狀態(tài)后,獲得互斥鎖,繼續(xù)執(zhí)行 sleep (1); gsub--; printf ("gsub=:%d\n",gsub); if (gsub == 50) { printf("resume thread1 at gsun = 5\n"); pthread_cond_signal(&cond);//讓掛起的線程繼續(xù)執(zhí)行 } pthread_mutex_unlock(&mutex); } pthread_exit (0); } 線程1和線程2不是應(yīng)該交替輸出的么?
為什么線程1輸出到50被掛起后線程2才會獲得互斥鎖呢?
HUH函數(shù)
2023-03-03 16:12:56