标签:
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <pthread.h> 4 5 int a = 200; 6 int b = 100; 7 pthread_mutex_t lock; 8 9 void* ThreadA(void*) 10 { 11 pthread_mutex_lock(&lock); //锁 12 a -= 50; 13 sleep(5); //执行到一半 使用sleep 放弃cpu调度 14 b += 50; 15 pthread_mutex_unlock(&lock); 16 } 17 18 void* ThreadB(void*) 19 { 20 sleep(1); //放弃CPU调度 目的先让A线程运行。 21 pthread_mutex_lock(&lock); 22 printf("%d\n", a + b); 23 pthread_mutex_unlock(&lock); 24 } 25 26 int main() 27 { 28 pthread_t tida, tidb; 29 pthread_mutex_init(&lock, NULL); 30 pthread_create(&tida, NULL, ThreadA, NULL); 31 pthread_create(&tidb, NULL, ThreadB, NULL); 32 pthread_join(tida, NULL); 33 pthread_join(tidb, NULL); 34 return 1; 35 }
程序执行结果
300
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5189251.html