用C语言设计线程,实现一个线程输出打印1-52,另一个线程打印A-Z, 输出的结果为: 12A34B......5152Z


前言

本文主要是用C语言来实现上面的功能,将介绍两种方法,一种需要用到条件锁,一种不需要条件锁。


提示:以下是本篇文章正文内容,下面案例可供参考

一、用条件锁来实现这个功能

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condNum;
static pthread_cond_t condAZ;


void* printNum(void* arg)//输出数字
{
	int a = 0;
	while (a<52)
	{
		pthread_mutex_lock(&mtx);
		pthread_cond_wait(&condAZ, &mtx);
		printf("%d",++a);
		printf("%d",++a);
		pthread_mutex_unlock(&mtx);
		pthread_cond_signal(&condNum);
	}
}

void* printAZ(void* arg)//输出字母
{
	char b = 'A';
	while (b<='Z')
	{
		pthread_mutex_lock(&mtx);
		pthread_cond_wait(&condNum, &mtx);
		printf("%c",b++);
		pthread_mutex_unlock(&mtx);
		pthread_cond_signal(&condAZ);
	}
}
int main()
{
	pthread_t threadNum;
	pthread_t threadAZ;

	pthread_cond_init(&condNum, NULL)
    
        
  
	pthread_cond_init(&condAZ, NULL);

	pthread_create(&threadNum, NULL, &printNum, NULL);
	pthread_create(&threadAZ, NULL, &printAZ, NULL);

	sleep(1);
	pthread_cond_signal(&condAZ);//唤醒打印数字

	pthread_join(threadNum, NULL);
	pthread_join(threadAZ, NULL);

	printf("\n");
	return 0;
}
	

二、不用条件锁来实现这个功能

代码如下(示例):

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
int lock = 0;

void* printNum(void* arg)
{
	int a = 0;
	while (a<52)
	{
		if(lock == 0)
		{
	
			printf("%d",++a);
			printf("%d",++a);//自增放在判断语句里面
			fflush(stdout);
			lock = 1;//用来唤醒输出字母
		}
	}
}

void* printAZ(void* arg)
{
	char b = 'A';
	while (b<='Z')
	{
		if(lock == 1)
		{
		
			printf("%c",b++);
			fflush(stdout);
		
			lock = 0;//用来唤醒输出数字
		}
	}
}
int main()
{
	pthread_t threadNum;
	pthread_t threadAZ;


	if(0!=pthread_create(&threadNum, NULL, &printNum, NULL))
	{
		perror("pthread_create");
		return -1;
	}
	if(0 !=	pthread_create(&threadAZ, NULL, &printAZ, NULL))
	{
		perror("pthread_create");
		return -1;
	}


	pthread_join(threadNum, NULL);
	pthread_join(threadAZ, NULL);

	printf("\n");
	return 0;
}


总结

         其实这两种方法都是可以的,一种是我们自己创造一个标志性变量,一个是利用C库函数,各有优势,希望对你有所帮助。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值