日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

pthread_mutex_lock用法

發(fā)布時間:2025/3/21 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pthread_mutex_lock用法 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

條件變量???

? 條件變量是利用線程間共享的全局變量進行同步的一種機制,主要包括兩個動作:一個線程等待"條件變量的條件成立"而掛起;另一個線程使"條件成立"(給出條件成立信號)。為了防止競爭,條件變量的使用總是和一個互斥鎖結(jié)合在一起。 ?

條件變量是利用線程間共享的全局變量進行同步的一種機制,主要包括兩個動作:
1)一個線程等待"條件變量的條件成立"而掛起;
2)另一個線程使"條件成立"(給出條件成立信號)。
為了防止競爭,條件變量的使用總是和一個互斥鎖結(jié)合在一起。

1.主要涉及到下面的函數(shù):
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr) ---動態(tài)創(chuàng)建條件變量

pthread_mutex_lock ---互斥鎖上鎖

pthread_mutex_unlock ----互斥鎖解鎖

pthread_cond_wait() / pthread_cond_timedwait -----等待條件變量,掛起線程,區(qū)別是后者,會有timeout時間,如 果到了timeout,線程自動解除阻塞,這個時間和 time()系統(tǒng)調(diào)用相同意義的。以1970年時間算起。

pthread_cond_signal ----激活等待列表中的線程,

pthread_cond_broadcast() -------激活所有等待線程列表中最先入隊的線程

注意:1)上面這幾個函數(shù)都是原子操作,可以為理解為一條指令,不會被其他程序打斷
? ? ? ? ? ?2)上面這個幾個函數(shù),必須配合使用。

? ? ? ? ? ?3)pthread_cond_wait,先會解除當前線程的互斥鎖,然后掛線線程,等待條件變量滿足條件。一旦條件變 ? ? ? ? ? ? ? ? ? 量滿足條件,則會給線程上鎖,繼續(xù)執(zhí)行pthread_cond_wait

?

2. 代碼實例
編譯:gcc thread_test.c -o thread_test -lpthread
------必須加上-lpthread,不然會報錯,找不到線程的相關(guān)函數(shù),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); } }

?

總結(jié)

以上是生活随笔為你收集整理的pthread_mutex_lock用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。