线程题目练习2

本文介绍了如何在C语言中使用线程和信号量实现字符串A1234567B的循环打印,并确保每次打印后字符串顺序倒置,通过sem_wait和sem_post操作实现并发控制。
摘要由CSDN通过智能技术生成

循环打印字符串,在使用线程的基础上,用信号量实现,打印一次,倒置一次。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>

char buf[] = "A1234567B";

//信号量
sem_t sem;
sem_t sem2;

//aa线程的执行体
void* test_a(void* arg)
{
	while(1)
	{
		//p操作 -1
		if(sem_wait(&sem) < 0)
		{
			perror("sem_wait");
			//pthread_exit(NULL);
		}
		//v操作 +1
		if(sem_post(&sem2) < 0)
		{
			perror("sem_post");
			//pthread_exit(NULL);
		}
		
		printf("buf = %s\n", buf);
	}
	pthread_exit(NULL);
}

//bb线程的执行体
void* test_b(void* arg)
{
	int i;
	int j = strlen(buf);
	char temp = 0;
	while(1)
	{
		//p操作 -1
		if(sem_wait(&sem2) < 0)
		{
			perror("sem_wait");
			//pthread_exit(NULL);
		}
		for(i=0; i<=j/2; i++)
		{
			temp = buf[i];
			buf[i] = buf[j-1-i];
			buf[j-1-i] = temp;
		}

		//v操作 +1
		if(sem_post(&sem) < 0)
		{
			perror("sem_post");
			//pthread_exit(NULL);
		}
		//printf("buf = %s\n", buf);

	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	//创建并初始化信号量
	if( sem_init(&sem, 0, 1) < 0)
	{
		perror("sem_init");
		return -1;
	}
	if( sem_init(&sem2, 0, 0) < 0)
	{
		perror("sem2_init");
		return -1;
	}

	//创建线程aa
	pthread_t aa;
	if( pthread_create(&aa, NULL, test_a, NULL) != 0)
	{
		fprintf(stderr, "pthread_create cuowu __%d__\n",__LINE__);
		return -1;
	}
	//创建线程bb
	pthread_t bb;
	if( pthread_create(&bb, NULL, test_b, NULL) != 0)
	{
		fprintf(stderr, "pthread_create cuowu __%d__\n",__LINE__);
		return -1;
	}
	
	pthread_join(aa,NULL); //阻塞等待
	pthread_join(bb,NULL); //阻塞等待
	
	//销毁信号量
	sem_destroy(&sem);
	sem_destroy(&sem2);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值