8.2作业

 定义一个全局变量,char str[] = "123456",要求定义两个线程:线程A, 线程B
1. 要求A线程循环打印全局字符串str;
2. 要求B线程循环倒置全局字符串str:将str中的内容倒置为"654321",再倒置为"123456"....
3. 要求A线程打印出的str字符串内容为:123456或者654321。
   不允许出现乱序,例如:623451 653451

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
char str[] = "1234567";
pthread_mutex_t mutex;
void*callback(void* arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		{
		printf("%s\n",str);
		}
		pthread_mutex_unlock(&mutex);
	}
	//sleep(1);
	pthread_exit(NULL);
}


void*callback2(void*arg)
{
	int len = strlen(str);
	int i = 0;
	char a;
	while(1)
	{
		pthread_mutex_lock(&mutex);
	 for(i=0;i<len/2;i++)
    {
		a=(*(str+i));
		*(str+i)=(*(str+len-1-i));
		*(str+len-i-1)=a;
	}
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	if(pthread_mutex_init(&mutex,NULL)!=0)
	{
		perror("mutex_create");
		return -1;
	}
	pthread_t tid1;
	if(pthread_create(&tid1,NULL,callback,NULL)!=0)
	{
		perror("pthread_create");
		return -1;
	}
	pthread_t tid2;
	if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
	{
		perror("pthread_create");
		return -1;
	}
	//while(1)
	//	sleep(1);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	pthread_mutex_destory(&mutex);
	return 0;
}

 要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>
#include<sys/stat.h>
#include<fcntl.h>
int res;
int flag=0;
pthread_mutex_t mutex;
void*print1(void*arg)
{

	int pp = open("./111",O_RDONLY);
	int dd = open("./222",O_WRONLY|O_CREAT|O_APPEND,0664);
	struct stat buf2;
	stat("./111",&buf2);
	int size1=buf2.st_size;
	char arr[20];
	//lock

	int num=0;
	while(1)
	{
		bzero(arr,sizeof(arr));
		res=read(pp,arr,sizeof(arr));
		num+=res;
		if(num>=size1/2)
		{
			break;
		}
		write(dd,arr,res);
	}

	pthread_exit(NULL);
}

void*print2(void*arg)
{	
	int pp = open("./111",O_RDONLY);
	int dd = open("./222",O_WRONLY|O_CREAT|O_APPEND,0664);
	char arr[20];
	struct stat buf2;
	stat("./111",&buf2);
	int size1=buf2.st_size;
    int num=0;
	//lock

	
	while(1)
	{
		bzero(arr,sizeof(arr));
		res=read(pp,arr,sizeof(arr));
		num+=res;
		if(num>=size1/2)
		{
			break;
		}
		write(dd,arr,res);
	}



	pthread_exit(NULL);

}

int arr[20];

int main(int argc, const char *argv[])
{

	pthread_t tid1,tid2;
	if(pthread_create(&tid1,NULL,print1,NULL)!=0)
	{
		perror("print1_creat");
		return -1;
	}
	if(pthread_create(&tid2,NULL,print2,NULL)!=0)
	{
		perror("print2_creat");
		return -1;
	}
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值