互斥锁与条件变量实现按照顺序打印ABC

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

#define PTHREAD_NUM 3

void *print_a(void *);
void *print_b(void *);
void *print_c(void *);

typedef void *(*pthread_func_t)(void *);

struct abc_demo{
	int flag;
	pthread_mutex_t mutex;
	pthread_cond_t cond;
	char *retval[PTHREAD_NUM];
	pthread_t tid_array[PTHREAD_NUM];
	pthread_func_t pfunc_array[PTHREAD_NUM];
};

struct abc_demo abc = {
	.pfunc_array = {print_a,print_b,print_c},
};
static int g_count = 0;
void *print_a(void *arg)
{
    while(1){

    		pthread_mutex_lock(&(abc.mutex));
    		while(abc.flag != 0){
    			 pthread_cond_wait(&(abc.cond), &(abc.mutex));
    		}
    		printf("A-----%d-----\n", g_count++);
    		abc.flag = 1;
    		pthread_mutex_unlock(&(abc.mutex));
    		pthread_cond_broadcast(&(abc.cond));
            sleep(1);
            if(g_count == 5)
                pthread_exit((void *) 1);
    	}
}

void *print_b(void *arg)
{
	while(1){
		pthread_mutex_lock(&(abc.mutex));
		while(abc.flag != 1){
			 pthread_cond_wait(&(abc.cond), &(abc.mutex));
		}
		printf("B\n");
		abc.flag = 2;
		pthread_mutex_unlock(&(abc.mutex));
		pthread_cond_broadcast(&(abc.cond));
		sleep(1);
        if(g_count == 5)
            pthread_exit((void *) 1);
	}
}

void *print_c(void *arg)
{	
	while(1){
		pthread_mutex_lock(&(abc.mutex));
		while(abc.flag != 2){
			 pthread_cond_wait(&(abc.cond),&(abc.mutex));
		}
		printf("C\n");
		abc.flag = 0;
		pthread_mutex_unlock(&(abc.mutex));
		pthread_cond_broadcast(&(abc.cond));
		sleep(1);
        if(g_count == 5)
            pthread_exit((void *) 1);
	}
}


int main(int argc, char const *argv[])
{
	int i,ret;
	abc.flag = 0;

	pthread_mutex_init(&(abc.mutex), NULL);
	pthread_cond_init(&(abc.cond),   NULL);

	for(i = 0; i < PTHREAD_NUM; i++)
    {
		ret = pthread_create(abc.tid_array+i, NULL, abc.pfunc_array[i], NULL);
		if(ret < 0)
        {
			perror("pthread_create");
			return -1;
		}
	} 
	
	for(i = 0; i < PTHREAD_NUM; i++)
    {
		ret = pthread_join(abc.tid_array[i],(void **)abc.retval+i);
		if(ret < 0)
		{
			perror("pthread_join");
			return -1;
		}
	}
	
	pthread_mutex_destroy(&(abc.mutex));
	pthread_cond_destroy(&(abc.cond));

	return 0;
}


测试结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值