多线程条件变量(pthread_cond_wait)用法
條件變量是利用線程間共享得全局變量進行同步的一種機制,主要包括兩個動作:一個線程等待“條件變量的條件成立”而掛起;另一個線程使“條件成立”給出條件成立信號。為了防止競爭,條件變量得使用總是和一個互斥鎖結合在一起。
1、創建和注銷
條件變量和互斥鎖一樣,有兩種創建方式,靜態方式使用PTHREAD_COND_INITIALIZER,動態方式使用pthread_coud_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr)函數,cond_attr設置為NULL即可。注銷需要使用int pthread_cond_destroy(pthread_cond_t *cond);
2、等待和激發
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)timewait方式表示超過時間條件沒有滿足則返回ETIMEOUT,結束等待 ,這個time是以絕對時間形式出現,即0表示格林尼治時間1970年1月1日0時0分0秒。為了防止多個線程同時請求pthread_cond_wait(),需要用互斥鎖(mutex)來限定phread_cond_wait()的操作。對cond的操作必須是互斥的。下面是配合pthread_cleanup_push(),pthread_cleanup_pop()的一個示例程序:
#include "pthread.h" #include "unistd.h" #include "stdio.h" #include "stdlib.h" #include "string.h"struct _Node {int number;struct _Node *next; }; typedef struct _Node Node;Node *head;/*信號量和條件變量*/ static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;/*線程異常時處理函數*/ static void cleanup_handler(void *arg) {printf("cleanup_handler\n");free(arg);(void)pthread_mutex_unlock(&mtx); }/* pthread_cleanup_push注冊一個回調函數,如果你的線程在對應的pthread_cleanup_pop之前異常退出(return是正常退出,其他是異常),那么系統就會執行這個回調函數(回調函數要做什么你自己決定)。但是如果在pthread_cleanup_pop之前沒有異常退出,pthread_cleanup_pop就把對應的回調函數取消了 */ static void* thread_func(void *arg) {Node *p = NULL;printf("in thread_func()\n");/*注冊線程異常處理函數*/pthread_cleanup_push(cleanup_handler, p);while (1){pthread_mutex_lock(&mtx);while (NULL != head){/*如果條件不滿足,則掛起*/pthread_cond_wait(&cond, &mtx);p = head;printf("Got %d from front of queue\n",p->number);free(p);pthread_mutex_unlock(&mtx);}}/*清空線程異常處理函數*/pthread_cleanup_pop(0);return 0; }int main() {pthread_t tid;int i;Node *p;pthread_create(&tid, NULL, thread_func, NULL);for(i = 0; i < 10; i++){printf("int main():%d", i);p = (Node*)malloc(sizeof(Node));p->number = i;pthread_mutex_lock(&mtx);p->next = head;head = p;/*通知條件OK了*/pthread_cond_signal(&cond);pthread_mutex_unlock(&mtx);sleep(1);}printf("thread 1 wanna end then cancel thread2.\n");pthread_cancel(tid);pthread_join(tid, NULL);printf("All done\n");return 0; }?輸出結果如下:
int main():0in thread_func() int main():1Got 1 from front of queue int main():2Got 2 from front of queue int main():3Got 3 from front of queue int main():4Got 4 from front of queue int main():5Got 5 from front of queue int main():6Got 6 from front of queue int main():7Got 7 from front of queue int main():8Got 8 from front of queue int main():9Got 9 from front of queue thread 1 wanna end then cancel thread2. cleanup_handler All done?
轉載于:https://www.cnblogs.com/binmaizhai/archive/2013/03/21/2973554.html
總結
以上是生活随笔為你收集整理的多线程条件变量(pthread_cond_wait)用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python学习笔记9-函数1
- 下一篇: 常用数据验证正则表达式释义(附:正则表达