标签:linux c linux编程 多线程程序设计 linux多线程 线程互斥
/* thread.c */ #include <stdio.h> #include <pthread.h> pthread_t thread[2]; int number = 0; pthread_mutex_t mut; void *work1() { int i = 0; printf("I am worker1\n"); for(i=0; i<10; i++) { pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); printf("worker1 number is %d\n",number); sleep(1); } pthread_exit(NULL); } void *work2() { int i = 0; printf("I am worker2\n"); for(i=0; i<10; i++) { pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); printf("worker2 number is %d\n",number); sleep(1); } pthread_exit(NULL); } int main() { pthread_mutex_init(&mut,NULL); //创建工人1线程 pthread_create(&thread[0],NULL,work1,NULL); //创建工人2线程 pthread_create(&thread[1],NULL,work2,NULL); //等待工人1线程的结束 pthread_join(thread[0],NULL); //等待工人2线程的结束 pthread_join(thread[1],NULL); return 0; }
[root@localhost share]# gcc -lpthread thread.c -o thread [root@localhost share]# ./thread I am worker2 worker2 number is 1 I am worker1 worker1 number is 2 worker2 number is 3 worker1 number is 4 worker1 number is 5 worker2 number is 6 worker2 number is 7 worker1 number is 8 worker1 number is 9 worker2 number is 10 worker1 number is 11 worker2 number is 12 worker2 number is 13 worker1 number is 14 worker2 number is 15 worker1 number is 16 worker1 number is 17 worker2 number is 18 worker2 number is 19 worker1 number is 20
标签:linux c linux编程 多线程程序设计 linux多线程 线程互斥
原文地址:http://blog.csdn.net/zhuwenfeng215/article/details/45562839