11.11-11.13练习

1、要求创建两个线程,以及一个全局变量,char str[] = "123456";

要求如下:

1)一个线程专门用于打印str;

2)另外一个线程专门用于倒置str字符串,不使用辅助数组。

3)要求打印出来的结果必须是123456或者654321,不能出现乱序情况,例如623451 653421

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
char str[]="123456";
//线程执行体
void* callBack(void* arg)
{
	int len =strlen(str);
	char temp;
	while(1)
	{
		for(int i=0;i<len/2;i++)
		{
			temp=str[i];
			str[i]=str[len-i-1];
			str[len-i-1]=temp;
		}
		sleep(1);
	}
}
int main(int argc, const char *argv[])
{
	//创建一个线程
	pthread_t tid;
	if(pthread_create(&tid,NULL,callBack,NULL) != 0)
	{
		perror("pthread_create");
		return -1;
	}
	printf("线程创建成功!\n");
	while(1)
	{
		printf("%s\n",str);
		sleep(1);
	}
	return 0;
}

2、要求用线程拷贝一张图片,一个线程拷贝前半部分,另一个线程拷贝后半部分

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

int fd,fw;
//线程执行体
void* callBack(void* arg)
{
	int i=0;
	int c=0;
	for(i=0;i<(*(int *)arg)/2;i++)
	{
		lseek(fd,i,SEEK_SET);
		lseek(fw,i,SEEK_SET);
		read(fd,&c,1);
		write(fw,&c,1);
	}
}
int main(int argc, const char *argv[])
{
	fd = open(argv[1],O_RDONLY);
	fw = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0777);
	if(fd < 0 || fw < 0)
	{
		perror("open");
		return -1;
	}
	off_t size = lseek(fd,0,SEEK_END);
	//创建一个线程
	pthread_t tid;
	if(pthread_create(&tid,NULL,callBack,(void*)&size) != 0)
	{
		perror("pthread_create");
		return -1;
	}
	printf("线程创建成功!\n");
	sleep(1);
	//打印
	int i=0;
	char c=0;
	for(i=size/2;i<size;i++){
		lseek(fd,i,SEEK_SET);
		lseek(fw,i,SEEK_SET);
		read(fd,&c,1);
		write(fw,&c,1);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值