多线程 3道题目 二

/*
    主线程和子线程之间的保序,
    子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次
*/


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

#define DEBUG 1
  
int num = 0;
int times = 0;

pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;

void* thread_func2(void *arg)
{
    while (times < 50) {
    
    pthread_mutex_lock(&mylock);
    
        //子线程在10~110中等待
        while(num >= 10 && num < 110 ){
            pthread_cond_wait(&qready, &mylock);
        }
        
        printf("%c", 'A');
        ++num;
        pthread_mutex_unlock(&mylock);
        pthread_cond_broadcast(&qready);
    }
    
    return (void *)0;
}

int main()
{
    pthread_t tid;
    int work = 0;
    void *tret;
    
    pthread_create(&tid, NULL, thread_func2, (void *)&work);

    while (times < 50) {
        pthread_mutex_lock(&mylock);

    //主线程在10内等待
        while(num < 10){
            pthread_cond_wait(&qready, &mylock);
        }

        printf("%c", 'B');
        num++;
        if (num == 110) {
            ++times;
            if (times == 50){
                pthread_cancel(tid);
            }
            num = 0;
        }
        
        pthread_mutex_unlock(&mylock);
        pthread_cond_broadcast(&qready);
    }
    
    pthread_join(tid, &tret);

    return  0;
}


 

转载于:https://my.oschina.net/leibornsean/blog/1577716

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值