华清远见上海中心22071班

. A线程 循环 打印str字符串。
2. B线程 循环 倒置str字符串,不使用辅助数组。注意是循环倒置,要把字符串倒过来,倒回去。
3. 要求A线程打印出来的结果是有序的

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
sem_t sem;
char str[]="123456";
//打印线程
void *callback_printf(void *arg)
{
	//申请信号量P操作
	if(sem_wait(&sem)<0)
	{
		perror("sem_wait");
	}
	while(1)
	{
		printf("%s\n", str);

	}
	//信号量V操作
	if(sem_post(&sem)<0)
	{
		perror("sem_post");
	}
		pthread_exit(NULL);
}
//负责倒置的线程
void *callback_reserve(void *arg)
{
	int temp;
	int i=0;
	//信号量p操作
	if(sem_wait(&sem)<0)
	{
		perror("sem_wait");
	}
	while(1)
	{
		for(i=0; i<strlen(str)/2; i++)
		{
			temp=str[i];
			str[i]=str[strlen(str)-1-i];
			str[strlen(str)-1-i]=temp;
		}
		printf("%s\n", str);
	}
	//信号量V操作
	if(sem_post(&sem)<0);
	{
		perror("sem_post");
	}
	pthread_exit(NULL);

}
int main(int argc, const char *argv[])
{
	//创建具有互斥锁性质的信号量
	
	if(sem_init(&sem, 0, 1)<0)
	{
		perror("sem_init");
		return -1;
	}
	//创建两个线程
	pthread_t tid1, tid2;
	//一个线程负责打印
	if(pthread_create(&tid1, NULL, callback_printf, NULL)!=0)
	{
		perror("pthread_create");
		return -1;
	}

	//一给负责倒置
	if(pthread_create(&tid1, NULL, callback_reserve, NULL)!=0)
	{
		perror("pthread_create");
		return -1;
	}
	//阻塞函数退出
	pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
	
	if(sem_destroy(&sem)<0)
	{
		perror("sem_destroy");
	}

	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值