Linux关于线程同步

关于线程的了解,可以阅读前一篇文章《Linux关于多线程技术》,了解线程后,阅读本文章会比较容易

以下代码是想让一个线程count进行累加,另一边读出来,每次累加就读出来一次

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>

int count = 0;

void *thr1(void *arg)
{
    while(1)
    {
       sleep(1);
       count+=10;
    }
}

void *thr2(void *arg)
{
    while(1)
    {
        printf("%d\n",count);
    }
}

int main()
{
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,thr1,NULL);
    pthread_create(&tid2,NULL,thr2,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
}

但是实际结果却不是这样的,会无限循环,两个线程不会进行同步

下面我们使用信号量,进行PV操作,让线程进行同步

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include <semaphore.h>

sem_t sem;
int count = 0;

void *thr1(void *arg)
{
    while(1)
    {
       sleep(1);
       sem_post(&sem);//V操作
       count+=10;
    }
}

void *thr2(void *arg)
{
    while(1)
    {
        sem_wait(&sem);//P操作
        printf("%d\n",count);
    }
}

int main()
{
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,thr1,NULL);
    pthread_create(&tid2,NULL,thr2,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
}

结果如下:实现线程同步

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值