声明锁变量:pthread_mutex_t mutex;
该变量有两种方式赋值:
1.mutex = PTHREAD_MUTEX_INITIALIZER;//使用静态数值
2.pthread_mutex_init(&mutex, NULL);//成功返回0,之后需要调用pthread_mutex_destroy(&mutex);
下面小程序 开两个线程开处理全局变量g_value;
如果注释掉程序中标志注释代码(互斥量),则运行结果如下
do the fun_2
mutex thread_2 sleep, stop thread_1 10 seconds
do the fun_1
thread 1 : 4168943360 g_value : 5
thread 1 unlock
thread 2 : 4160550656 g_value : 5
thread 2 unlock
main g_value : 5
如果打开互斥量代码,则运行结果如下:
do the fun_2
mutex thread_2 sleep, stop thread_1 10 seconds
· thread 2 : 2579085056 g_value : 6
thread 2 unlock
do the fun_1
thread 1 : 2587477760 g_value : 5
thread 1 unlock
main g_value : 5
对比两个结果,可知,使用了互斥量锁时,当thread2拿到锁时,thread1处于 阻塞态,达到同步效果
互斥量关键函数:
pthread_mutex_t;//锁类型
pthread_mutex_init(&mutex);//初始化锁
pthread_mutex_lock(&mutex);//锁住线程
pthread_mutex_unlock(&mutex);//打开锁
pthread_mutex_trylock(&mutex);//待了解
pthread_mutex_destroy(&mutex);//
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <pthread.h>
5
6 int g_value = 1;
7 //pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//这是一种初始化方式,也可以使用pthread_mutex_init(mutex);
8 pthread_mutex_t mutex;
9
10
11 void* fun_1(void){
12
13 //注释1
14 // pthread_mutex_lock(&mutex);//拿到锁
15
16 printf("do the fun_1\n");
17
18 g_value = 0;
19 g_value += 5;
20
21 printf("thread 1 : %u g_value : %d\n",(unsigned int)pthread_self(), g_value);
22 //注释2
23 //pthread_mutex_unlock(&mutex);//解锁
24
25 printf("thread 1 unlock\n");
26 return(void*)1;
27 }
28
29 void* fun_2(void){
30
31 //注释3
32 // pthread_mutex_lock(&mutex);//拿到锁
33
34 printf("do the fun_2\n");
35
36 g_value = 0;
37 g_value += 6;
38
39 printf("mutex thread_2 sleep, stop thread_1 10 seconds\n");
40 sleep(10);
41
42 printf("thread 2 : %u g_value : %d\n",(unsigned int)pthread_self(), g_value);
43
44 //注释4
45 // pthread_mutex_unlock(&mutex);//解锁
46
47 printf("thread 2 unlock\n");
48 return(void*)1;
49 }
51 int main(void){
52 pthread_t tid_1;
53 pthread_t tid_2;
54
55 if(pthread_mutex_init(&mutex, NULL)){//动态初始化mutex
56 printf("mutex init err\n");
57 exit(1);
58 }
59
60
61 if(pthread_create(&tid_1, NULL, (void*)fun_1, NULL)){
62 printf("pthread_craete 1 error\n");
63 exit(1);
64 }
65
66 if(pthread_create(&tid_2, NULL, (void*)fun_2, NULL)){
67 printf("pthread_craete 2 error\n");
68 exit(1);
69 }
70
71 pthread_join(tid_1, NULL);
72 pthread_join(tid_2, NULL);
73
74 printf("main g_value : %d\n",g_value);
75
76 if(pthread_mutex_destroy(&mutex)){//销毁锁
77 printf("destroy mutex err\n");
78 exit(1);
79 }
80 return 0;
81 }