线程的同步与互斥
A.mutex(互斥量)
+1操作:从内存读变量到寄存器->寄存器的值加1->将寄存器的值写回内存
举一个例子:
1 #include<stdio.h>
2 #include<pthread.h>
3 static int g_count=0;
4 void *print_bug(void*arg)
5 {
6 //int index=0;
7 int tmp=0;
8 while(tmp++<10)
9 {
10 printf("this is thread %d,count is:%d\n",(int)arg,++g_count);
11 //g_count=index++;
12
13 }
14
15
16
17
18 }
19
20 int main()
21 {
22 pthread_t tid1,tid2;
23 pthread_create(&tid1,NULL,print_bug,(void*)1);
24 pthread_create(&tid2,NULL,print_bug,(void*)2);
25 void*ret=NULL;
26 pthread_join(tid1,&ret);
27 pthread_join(tid2,&ret);
28
29
30
31 return 0;
32 }若放开inedex,运行结果:
这样的话两个线程会相互干扰,影响个g_count的值。
要解决上述问题就需用互斥量,即加锁。定义一个全局锁:pthread_mutex lock=PTHREAD_MUTEX_INITIALIIER;
本文出自 “输出菱形图案” 博客,请务必保留此出处http://10541571.blog.51cto.com/10531571/1765150
原文:http://10541571.blog.51cto.com/10531571/1765150