目录
2、要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分(不允许使用sleep函数,不允许使用flag)
1、定义一个全局变量,char str[] = "123456",要求定义两个线程:线程A, 线程B
1) 要求A线程循环打印全局字符串str;
2) 要求B线程循环倒置全局字符串str:将str中的内容倒置为"654321",再倒置为"123456"....
注意:是倒置不是倒着打印
代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<pthread.h>
#include<string.h>
char str[] = "123456";
int flag;
void *funA(void *arg)
{
while(1)
{
if(flag == 0)
{
printf("线程A---%s\n",str);
flag=1;
sleep(1);
}
}
pthread_exit(NULL);
}
void *funB(void *arg)
{
while(1)
{
if(flag == 1)
{
char temp;
int j=5;
for(int i=0;i<strlen(str)/2;i++)
{
temp=str[i];
str[i]=str[j-i];
str[j-i]=temp;
}
printf("线程B---str = %s\n",str);
flag=0;
sleep(1);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,funA,NULL) != 0)
{
perror("pthread_create");
return -1;
}
printf("创建A线程成功\n");
if(pthread_create(&tid,NULL,funB,NULL) != 0)
{
perror("pthread_create");
return -1;
}
printf("创建B线程成功\n");
printf("---这是主线程---\n");
pthread_join(tid,NULL);
printf("分支线程退出\n");
}
执行结果:
2、要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
(不允许使用sleep函数,不允许使用flag)
代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<pthread.h>
#include<string.h>
#include<strings.h>
pthread_mutex_t mutex;
int *pfd_r,*pfd_w;
void *funA(void *arg)
{
pthread_mutex_lock(&mutex);
char buf;
int a = lseek(*pfd_r,0,SEEK_END);
lseek(*pfd_r,0,SEEK_SET);
lseek(*pfd_w,0,SEEK_SET);
for(int i=0;i<a/2;i++)
{
ssize_t res = read(*pfd_r,&buf,1);
ssize_t res2 = write(*pfd_w,&buf,1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *funB(void *arg)
{
pthread_mutex_lock(&mutex);
char buf;
int a = lseek(*pfd_r,0,SEEK_END);
lseek(*pfd_r,a/2,SEEK_SET);
lseek(*pfd_w,0,SEEK_END);
for(int i=a/2;i<a;i++)
{
ssize_t res = read(*pfd_r,&buf,1);
if(res == 0)
{
break;
}
ssize_t res2 = write(*pfd_w,&buf,1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
int fd_r = open("./2022-07-19 16-31-05 的屏幕截图.png",O_RDONLY);
int fd_w = open("copy.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
// int a = lseek(fd_r,0,SEEK_END);
pfd_r=&fd_r;
pfd_w=&fd_w;
if(pthread_mutex_init(&mutex,NULL) != 0)
{
perror("pthread_mutex_init");
return -1;
}
printf("mutex_init success\n");
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,funA,NULL) != 0)
{
perror("pthread_create");
return -1;
}
printf("创建A线程成功\n");
pthread_join(tid1,NULL);
if(pthread_create(&tid2,NULL,funB,NULL) != 0)
{
perror("pthread_create");
return -1;
}
printf("创建B线程成功\n");
pthread_join(tid2,NULL);
close(fd_r);
close(fd_w);
pthread_mutex_destroy(&mutex);
printf("分支线程退出\n");
return 0;
}
执行结果: