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

来源:互联网 发布:记考勤软件 编辑:程序博客网 时间:2024/04/27 07:48
/*****************************************************
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