生活随笔
收集整理的這篇文章主要介紹了
pthread_mutex_lock用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
條件變量???
? 條件變量是利用線程間共享的全局變量進行同步的一種機制,主要包括兩個動作:一個線程等待"條件變量的條件成立"而掛起;另一個線程使"條件成立"(給出條件成立信號)。為了防止競爭,條件變量的使用總是和一個互斥鎖結合在一起。 ?
條件變量是利用線程間共享的全局變量進行同步的一種機制,主要包括兩個動作:
1)一個線程等待"條件變量的條件成立"而掛起;
2)另一個線程使"條件成立"(給出條件成立信號)。
為了防止競爭,條件變量的使用總是和一個互斥鎖結合在一起。
1.主要涉及到下面的函數:
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr) ---動態創建條件變量
pthread_mutex_lock ---互斥鎖上鎖
pthread_mutex_unlock ----互斥鎖解鎖
pthread_cond_wait() / pthread_cond_timedwait -----等待條件變量,掛起線程,區別是后者,會有timeout時間,如 果到了timeout,線程自動解除阻塞,這個時間和 time()系統調用相同意義的。以1970年時間算起。
pthread_cond_signal ----激活等待列表中的線程,
pthread_cond_broadcast() -------激活所有等待線程列表中最先入隊的線程
注意:1)上面這幾個函數都是原子操作,可以為理解為一條指令,不會被其他程序打斷
? ? ? ? ? ?2)上面這個幾個函數,必須配合使用。
? ? ? ? ? ?3)pthread_cond_wait,先會解除當前線程的互斥鎖,然后掛線線程,等待條件變量滿足條件。一旦條件變 ? ? ? ? ? ? ? ? ? 量滿足條件,則會給線程上鎖,繼續執行pthread_cond_wait
?
2. 代碼實例
編譯:gcc thread_test.c -o thread_test -lpthread
------必須加上-lpthread,不然會報錯,找不到線程的相關函數,gcc自身沒有連接線
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*初始化互斥鎖*/
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//init condvoid *thread1(void*);
void *thread2(void*);int i = 1; //globalint main(void){pthread_t t_a;pthread_t t_b;//two threadpthread_create(&t_a,NULL,thread2,(void*)NULL);pthread_create(&t_b,NULL,thread1,(void*)NULL);//Create threadprintf("t_a:0x%x, t_b:0x%x:", t_a, t_b);pthread_join(t_b,NULL);//wait a_b thread endpthread_mutex_destroy(&mutex);pthread_cond_destroy(&cond);exit(0);
}void *thread1(void *junk){for(i = 1;i<= 9; i++){pthread_mutex_lock(&mutex); //互斥鎖printf("call thread1 \n");if(i%3 == 0){pthread_cond_signal(&cond); //send sianal to t_bprintf("thread1:******i=%d\n", i);}elseprintf("thread1: %d\n",i);pthread_mutex_unlock(&mutex);printf("thread1: sleep i=%d\n", i);sleep(1);printf("thread1: sleep i=%d******end\n", i);}
}void *thread2(void*junk){while(i < 9){pthread_mutex_lock(&mutex);printf("call thread2 \n");if(i%3 != 0)pthread_cond_wait(&cond,&mutex); //waitprintf("thread2: %d\n",i);pthread_mutex_unlock(&mutex);printf("thread2: sleep i=%d\n", i);sleep(1);printf("thread2: sleep i=%d******end\n", i); }
}
?
總結
以上是生活随笔為你收集整理的pthread_mutex_lock用法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。