两个线程轮流对一个全局变量执行加1操作并且打印

13 篇文章 0 订阅

两个线程轮流对一个全局变量执行加1操作并且打印

最近在看多线程编程,想起以前有个电话面试出的题目,今天就写了下,主要是利用互斥变量和条件变量,主线程先执行,然后通知子线程执行,轮流执行++操作,并且打印,代码如下:

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

using namespace std;

int num = 0;
pthread_mutex_t mtx;
pthread_cond_t cond;

unsigned char flag = 3;   //00000011

static void* threadFunc(void *arg)
{
    int loop = *(int*)arg;

    while(num < loop)
    {
        pthread_mutex_lock(&mtx);
        while((flag >> 1) & 0x1)
            pthread_cond_wait(&cond, &mtx);

        ++num;
        flag &= 0x0;
        flag |= 0x2;
        printf("subthread:%u ,num=%d\n",pthread_self(),num);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mtx);
    }
    return NULL;
}

int main()
{
    pthread_mutex_init(&mtx, NULL);
    pthread_cond_init(&cond, NULL);
    int loop = 200;
    pthread_t t;

    pthread_create(&t, NULL, threadFunc, &loop);

    flag &= 0xfe;
    while(num < loop)
    {
        pthread_mutex_lock(&mtx);
        while(flag & 0x1)
        {
            pthread_cond_wait(&cond, &mtx);
        }
        ++num;
        flag &= 0x0;
        flag |= 0x1;
        printf("main:%u ,i=%d\n",pthread_self(),num);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mtx);
    }

    pthread_join(t, NULL);

    pthread_mutex_destroy(&mtx);
    pthread_cond_destroy(&cond);
    return 0;
}

其实也可以不用条件变量,利用那个标志也能达到同样的效果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值