多线程打印出ABCABCABC...

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

/* mutex.c */
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>

/* 全局变量 */
int gnum = 0;
/* 互斥量 */
pthread_mutex_t mutex;

/* 声明线程运行服务程序. */
static void pthread_func(void*);
pthread_cond_t qready=PTHREAD_COND_INITIALIZER;

int main (void)
{
 /*线程的标识符*/
  pthread_t pt[3]; 
  int ret = 0;

  /* 互斥初始化. */
  pthread_mutex_init(&mutex, NULL);
  /*分别创建线程1、2*/
  for(int i=0;i<3;i++)
  {
  ret = pthread_create(pt+i,  //线程标识符指针
                       NULL,  //默认属性
                       (void*)pthread_func, //运行函数
                       i); //无参数
  }

  
 
  pthread_join(pt[0], NULL);
  pthread_join(pt[1], NULL);
  pthread_join(pt[2], NULL);
  return 0;
}


/*线程2的服务程序*/
static void pthread_func(void *arg)
{
  int flag = (int)arg;
  int i = 0;

  for (i=0; i<10; i++)  {
    pthread_mutex_lock(&mutex); /* 获取互斥锁. */
    while(gnum%3 != flag ){
		pthread_cond_wait(&qready, &mutex);
	}
	gnum ++ ;
	printf("%c",flag+'A');
    pthread_mutex_unlock(&mutex);
    pthread_cond_broadcast(&qready);

  }
  pthread_exit (NULL);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值