题目: 编写一个程序,开启3个线程,这3个线程的ID分别对应字符A、B、C,每个线程将自己对应的字符在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
代码示例:
#include <stdio.h>
#include <pthread.h>
typedef struct _tagThreadInfo
{
unsigned int uiPrtSqNoInBlk;//This member indicates which thread ID will be printed.A<-->0, B<-->1,C<--->2
unsigned int uiTimesOfPrinting;//30 is the max times in this example
pthread_mutex_t mutex;
pthread_cond_t ReadyToPrint;//Ready to print the next thread ID
pthread_cond_t JobFinished;//All the job required is finished
} Thread_Info_t;
static Thread_Info_t s_ThreadInfo =
{
.uiPrtSqNoInBlk = 0,
.uiTimesOfPrinting = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.ReadyToPrint = PTHREAD_COND_INITIALIZER,
.JobFinished = PTHREAD_COND_INITIALIZER,
};
void* thread_func(void *arg)
{
int param = (int) arg;
int i;
for(i = 0; i < 10; i++)
{
pthread_mutex_lock( &s_ThreadInfo.mutex );
while ( s_ThreadInfo.uiPrtSqNoInBlk != param )
pthread_cond_wait(&s_ThreadInfo.ReadyToPrint, &s_ThreadInfo.mutex);
printf("%c", param + 'A');
s_ThreadInfo.uiPrtSqNoInBlk++;
s_ThreadInfo.uiTimesOfPrinting ++;
( s_ThreadInfo.uiPrtSqNoInBlk) = ( s_ThreadInfo.uiPrtSqNoInBlk) % 3;
pthread_mutex_unlock(&s_ThreadInfo.mutex);
pthread_cond_broadcast(&s_ThreadInfo.ReadyToPrint);
if ( s_ThreadInfo.uiTimesOfPrinting == 30 )
pthread_cond_broadcast( &s_ThreadInfo.JobFinished );
}
return (void *)0;
}
int main()
{
int i;
pthread_t tid[3];
void *tret;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for(i = 0; i < 3; i++)
pthread_create(&tid[i], &attr, thread_func, (void *) i);
pthread_cond_wait(&s_ThreadInfo.JobFinished, &s_ThreadInfo.mutex);
}
编译:
/opt/inter-test# gcc -g -o threadExample threadExample.c -lpthread
运行结果:
/opt/inter-test# ./threadExample
ABCABCABCABCABCABCABCABCABCABC