【练】要求定义一个全局变量 char buf[] = “1234567“,创建两个线程,不考虑退出条件,打印buf

5 篇文章 0 订阅
3 篇文章 0 订阅

        要求定义一个全局变量 char buf[] = "1234567",创建两个线程,不考虑退出条件,另:

  1. A线程循环打印buf字符串,
  2. B线程循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321. 不打印!!
  3. 倒置不允许使用辅助数组。
  4. 要求A线程打印出来的结果只能为 1234567 或者 7654321 不允许出现7634521 7234567
  5. 不允许使用sleep函数

方法一:使用flag将其分离

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <head.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>

char buf[]="1234567";
int flag= 0 ;

void* callback_1(void* arg)//打印
{
	while(1)
	{
		if(0 == flag)
		{
			printf("%s\n",buf);
			flag=1;
		}
	}
	pthread_exit(NULL);
}

void* callback_2(void* arg)//逆置 不打印
{
	char t=0;
	while(1)
	{
		if(1 == flag)
		{
			for(int i=0;i<strlen(buf)/2;i++)
			{
				t=buf[i];
				buf[i] = buf[strlen(buf)-1-i];
				buf[strlen(buf)-1-i] = t;
			}
			flag=0;
		}
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	pthread_t tid_1,tid_2;
	if(pthread_create(&tid_1,NULL,callback_1,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
		return -1;
	}
	pthread_detach(tid_1);  //分离线程1
	if(pthread_create(&tid_2,NULL,callback_2,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
		return -1;
	}

	pthread_join(tid_2,NULL);
	printf("主线程准备退出");
	return 0;
}

 方法二:使用互斥锁

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <head.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
//临界资源
char buf[]="1234567";

//互斥锁
pthread_mutex_t mutex;

void* callback_1(void* arg)//打印
{
	while(1)
	{
		/***********临界区**************/
		//上锁
		pthread_mutex_lock(&mutex);

		printf("%s\n",buf);

		//解锁
		pthread_mutex_unlock(&mutex);
		/***********临界区**************/
	}
	pthread_exit(NULL);
}

void* callback_2(void* arg)//逆置 不打印
{
	char t=0;
	while(1)
	{
		/***********临界区**************/
		//上锁
		pthread_mutex_lock(&mutex);

		for(int i=0;i<strlen(buf)/2;i++)
		{
			t=buf[i];
			buf[i] = buf[strlen(buf)-1-i];
			buf[strlen(buf)-1-i] = t;
		}
		//解锁
		pthread_mutex_unlock(&mutex);
		/***********临界区**************/
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	//申请一个互斥锁
	pthread_mutex_init(&mutex,NULL);

	pthread_t tid_1,tid_2;
	if(pthread_create(&tid_1,NULL,callback_1,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
		return -1;
	}
	pthread_detach(tid_1);  //分离线程1

	if(pthread_create(&tid_2,NULL,callback_2,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
		return -1;
	}

	pthread_join(tid_2,NULL);  //阻塞等待线程2退出
	
	//销毁互斥锁
	pthread_mutex_destroy(&mutex);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值