通过互斥锁来防止线程冲突

Posted on 2012-05-21 15:22  逝水如年  阅读(343)  评论(0)    收藏  举报
 1 /*pthread_mutex.c*/
 2 #include <pthread.h>
 3 #include <stdlib.h>
 4 #include <stdio.h>
 5 #define MAX_LOOP 5000
 6 int counter;
 7 pthread_mutex_t p_m_t;
 8 pthread_t p_tA,p_tB;
 9 //通过互斥锁来防止多线程造成数据冲突
10 void *fnc(void * a)
11 {
12     int i,val;
13     for (i = 0; i < MAX_LOOP; i++)
14     {
15         /*线程1锁定,线程2等待解锁再执行,这个程序无论怎么执行都会加到10000
16          *去掉互斥锁数据数据不会总加到10000,因为线程冲突引起的
17          */
18         pthread_mutex_lock(&p_m_t);
19         val = counter;
20         printf("this is %x: %d\n", (unsigned int)pthread_self(), (val + 1));
21         counter = val + 1;
22         pthread_mutex_unlock(&p_m_t);
23     }
24     return (void *)1;
25 }
26 
27 int main()
28 {
29     //创建两个线程
30     pthread_create(&p_tA, NULL, &fnc, NULL);
31     pthread_create(&p_tB, NULL, &fnc, NULL);
32     pthread_join(p_tA, NULL);
33     pthread_join(p_tB, NULL);
34     return 1;
35 }

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3