浅析一道多线程笔试题

      题目: 编写一个程序,开启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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值