envy2002 发表于 2013-1-31 02:49:34

linux多线程2

下面我们将上面两个线程进行同步。
 
#include <pthread.h>#include <stdio.h>#include <unistd.h>//初始化一个mutex(互斥体).pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;//define the first thread procedue.void * thread_1_pro(void * arg){int * p_int_a=(int *) arg;while(1){pthread_mutex_lock(&counter_mutex);printf("------------- a = %d\n",*p_int_a);(*p_int_a)++; sleep(7);printf("+++++++++++++ a = %d\n",*p_int_a);pthread_mutex_unlock(&counter_mutex);//must add this sleep, give the chance to wake up thread_2_pro.    sleep(3);    }}void * thread_2_pro(void * arg){int * p_int_a=(int *) arg;while(1){pthread_mutex_lock(&counter_mutex);printf("------------- b = %d\n",*p_int_a);(*p_int_a)++;sleep(3);printf("+++++++++++++ b = %d\n",*p_int_a);pthread_mutex_unlock(&counter_mutex);//must add this sleep, give the chance to wake up thread_1_pro.      sleep(3);   }}int main(int argc, char ** argv){pthread_t tidA, tidB;    int common=0;pthread_create(&tidA, NULL, &thread_1_pro, &common);pthread_create(&tidB, NULL, &thread_2_pro, &common);sleep(120);//为什么需要最下面两行呢,如果没有,12秒后,主进程结束,会自动回收线程tidA, tidB,//这两行就是主进程中的线程要等这两个分支线程结束后,才执行join后面的内容。//pthread_join(tidA, NULL);//pthread_join(tidB, NULL);return 0;return 0;}    输出结果:
    可以看到,linux多线程和java多线程几乎一摸一样的。唯一的区别,好像就是在mutex后面必须加个sleep,有更多
    的机会让别的线程获得机会去执行,如果不加这个,执行结果是完全不一样的。
------------- a = 0+++++++++++++ a = 1------------- b = 1+++++++++++++ b = 2------------- a = 2+++++++++++++ a = 3------------- b = 3+++++++++++++ b = 4------------- a = 4+++++++++++++ a = 5------------- b = 5+++++++++++++ b = 6------------- a = 6+++++++++++++ a = 7------------- b = 7+++++++++++++ b = 8------------- a = 8
页: [1]
查看完整版本: linux多线程2