to myself 的分类学习日志

做自己想做的事
posts - 232, comments - 6, trackbacks - 0, articles - 0

Mutex and Condition variable

Posted on 2014-11-12 17:54 kongkongzi 阅读(288) 评论(0)  编辑 收藏 引用 所属分类: c++ programming
Mutex and Condition variable in Linux:
 1 int g_value = 0;
 2 pthread_mutex_t g_pthread_mutex;
 3 pthread_cond_t g_pthread_cond;
 4 
 5
 6 void* ThreadFunc1(void* args)
 7 {
 8     pthread_mutex_lock(&g_pthread_mutex);
 9 
10     printf("ThreadFunc1\n");
11 
12     pthread_cond_wait(&g_pthread_cond, &g_pthread_mutex);
13 
14     g_value = 1;
15     sleep(2);
16     printf("ThreadFunc1: g_value=%d.\n", g_value);
17 
18     pthread_mutex_unlock(&g_pthread_mutex);
19     return NULL;
20 }
21 
22 
23 void* ThreadFunc2(void* args)
24 {
25     pthread_mutex_lock(&g_pthread_mutex);
26 
27     printf("ThreadFunc2\n");
28 
29     pthread_cond_signal(&g_pthread_cond);
30 
31 
32     g_value = 2;
33     sleep(2);
34     printf("ThreadFunc2: g_value=%d.\n", g_value);
35 
36     pthread_mutex_unlock(&g_pthread_mutex);
37     return NULL;
38 }
 1 int main(int argc, char **argv)
 2 {
 3     if (pthread_mutex_init(&g_pthread_mutex, NULL) != 0)
 4     {
 5         printf("fail to initial thread mutex.\n");
 6         return -1;
 7     }
 8 
 9     if (pthread_cond_init(&g_pthread_cond, NULL) != 0)
10     {
11         printf("fail to initial thread condition.\n");
12         return -1;
13     }
14 
15     pthread_t thread1;
16     int ret = pthread_create(&thread1, NULL, ThreadFunc1, NULL);
17     if (ret != 0)
18     {
19         printf("fail to create thread 1.\n");
20         return -1;
21     }
22 
23     pthread_t thread2;
24     ret = pthread_create(&thread2, NULL, ThreadFunc2, NULL);
25     if (ret != 0)
26     {
27         printf("fail to create thread 2.\n");
28         return -1;
29     }
30 
31     pthread_join(thread1, NULL);
32     pthread_join(thread2, NULL);
33 
34   return 0;
35 }
输出:
ThreadFunc1
ThreadFunc2
ThreadFunc2: g_value=2.
ThreadFunc1: g_value=1.

Mutex and Condition variable in Windows:
HANDLE event
CreateEvent
SetEvent
ResetEvent
WaitForSingleObject

HANDLE mutex
CreateMutex
ReleaseMutex
WaitForSingleObject
注:Windows HANDLE类型可以为Event,Mutex,Process,Thread,Semaphore等。

说明:
1. C++在使用时,一般封装设计class Mutex,提供lock、unlock等函数,和设计class Monitor(boost::condition_variable_any),提供wait、notify等函数。

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理