编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co.,     Ltd. 
File name:
Author:Jerey_Jobs    Version:0.1    Date: 
Description:
Funcion List: 
*****************************************************/

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

#define N 10

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condA_B = PTHREAD_COND_INITIALIZER;
pthread_cond_t condB_C = PTHREAD_COND_INITIALIZER;
pthread_cond_t condC_A = PTHREAD_COND_INITIALIZER;

int flagA = 0,flagB = 0,flagC = 0;

void *th_fun1(void *arg)
{
int i = 0;
char *name = (char *)arg;
while(i < N)
{
pthread_mutex_lock(&mutex);
        flagA = 1;
pthread_cond_wait(&condC_A, &mutex);
flagA = 0;
printf("%c:%d-->%lx\n", *name, i, pthread_self());
while(!flagB)
{
pthread_mutex_unlock(&mutex);
usleep(10);
pthread_mutex_lock(&mutex);
}
pthread_cond_signal(&condA_B);
pthread_mutex_unlock(&mutex);
i++;
usleep(10);
}
flagA = 1;
}

void *th_fun2(void *arg)
{
int i = 0;
char *name = (char *)arg;
while(i < N)
{
pthread_mutex_lock(&mutex);
flagB = 1;
pthread_cond_wait(&condA_B, &mutex);
flagB = 0;
printf("%c:%d-->%lx\n",*name, i, pthread_self());
while(!flagC)
{
pthread_mutex_unlock(&mutex);
usleep(10);
pthread_mutex_lock(&mutex);
}
pthread_cond_signal(&condB_C);
pthread_mutex_unlock(&mutex);
i++;
usleep(10);
}
}

void *th_fun3(void * arg)
{
int i = 0;
char *name = (char *)arg;
while(i < N)
{
pthread_mutex_lock(&mutex);
flagC = 1;
pthread_cond_wait(&condB_C, &mutex);
flagC = 0;
printf("%c:%d-->%lx\n", *name, i, pthread_self());
while(!flagA)
{
pthread_mutex_unlock(&mutex);
usleep(10);
pthread_mutex_lock(&mutex);
}
pthread_cond_signal(&condC_A);
pthread_mutex_unlock(&mutex);
i++;
usleep(10);
}
}

int main()
{
pthread_t th1, th2, th3;
int ret = 0;
char name1 = 'A', name2 = 'B', name3 = 'C';
int *p1 = (int *) &name1;
int *p2 = (int *) &name2;
int *p3 = (int *) &name3;

ret = pthread_create(&th1, NULL, th_fun1, (void *)p1);
if(ret)
{
printf("create th_fun1 error!\n");
return 1;
}
usleep(10);
ret = pthread_create(&th2, NULL, th_fun2, (void *)p2);
if(ret)
{
printf("create th_fun2 error!\n");
return 1;
}
usleep(10);
ret = pthread_create(&th3, NULL, th_fun3, (void *)p3);
if(ret)
{
printf("create th_fun3 error!\n");
return 1;
}
   
pthread_cond_broadcast(&condC_A);
pthread_join(th1, NULL);
printf("th1 finished!\n");
pthread_join(th2, NULL);
printf("th2 finished!\n");
pthread_join(th3, NULL);
printf("th3 finished!\n");

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值