20230803

1.创建2个子线程,拷

总字节大小size为: 619790
A创建成功
B创建成功
A拷贝完成
A拷贝完成
ubuntu@ubuntu:X1$ ls
copy.png  core  k1  k1.c  t1  t1.c
ubuntu@ubuntu:X1$ eog copy.png
ubuntu@ubuntu:X1$ cat k1.c
#include <head.h>
#include <pthread.h>


pthread_mutex_t mutex;

off_t size;
int fp;
int fpw;
 
void* TidB(void* arg);
void* TidB(void* arg)
{
	pthread_mutex_lock(&mutex);
	char s1 = 0;
	lseek(fp,size/2,SEEK_SET);
	lseek(fpw,size/2,SEEK_SET);
	for(int i=size/2;i<size;i++)
	{
		read(fp,&s1,1);
		write(fpw,&s1,1);
	}
	pthread_mutex_unlock(&mutex);
	pthread_exit(NULL);

}

void* Atid(void* arg);
void* Atid(void* arg)
{
	pthread_mutex_lock(&mutex);
	char s1 = 0;	
	lseek(fp,0,SEEK_SET);
	lseek(fpw,0,SEEK_SET);
	for(int i=0;i<size/2;i++)
	{
		read(fp,&s1,1);
		write(fpw,&s1,1);
	}
	pthread_mutex_unlock(&mutex);
	pthread_exit(NULL);

}

int main()
{
	fp = open("/home/ubuntu/Kple.png",O_RDONLY);
	if(fp < 0)
	{
		perror("openr");
		return -1;
	}

	fpw = open("copy.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
	if(fpw < 0)
	{
		perror("openw");
		return -1;
	}
	size = lseek(fp,0,SEEK_END);
	printf("总字节大小size为: %ld\n",size);

	pthread_mutex_init(&mutex,NULL);
	pthread_t tida;
	pthread_t tidb;
	if(pthread_create(&tida,NULL,TidB,NULL) != 0)
	{
		printf("pthread_create error  __%d__\n",__LINE__);
		return -1;
	}
	printf("A创建成功\n");
	if(pthread_create(&tidb,NULL,Atid,NULL) != 0)
	{
		printf("pthread_create error  __%d__\n",__LINE__);
		return -1;
	}
	printf("B创建成功\n");

	
	pthread_join(tida,NULL);
	printf("A拷贝完成\n");
	pthread_join(tidb,NULL);
	printf("A拷贝完成\n");

	pthread_mutex_destroy(&mutex);

	close(fp);
	close(fpw);


	return 0;
}

贝图片文件,各线程各拷贝一办;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值