linux多线程异常,linux 多线程

场景:linux多线程二

linux多线程2

下面我们将上面两个线程进行同步。

#include

#include

#include

//初始化一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值