定义一个全局变量,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<pthread.h>
#include<string.h>
char str[]="123456";
pthread_mutex_t mutex; //互斥锁
void *func(void *arg)
{
while(1)
{
char temp;
pthread_mutex_lock(&mutex); //上锁
for(int i=0;i<strlen(str)/2;i++)
{
temp=str[i];
str[i]=str[strlen(str)-1-i];
str[strlen(str)-1-i]=temp;
}
pthread_mutex_unlock(&mutex); //解锁
}
pthread_exit(NULL);
}
void *func2(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
printf("%s\n",str);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建互斥锁,并初始化
if(pthread_mutex_init(&mutex, NULL) != 0)
{
perror("pthread_mutex_init");
return -1;
}
pthread_t tid,tid2;
if(pthread_create(&tid,NULL,func,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,func2,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid,NULL);
pthread_join(tid2,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
2. 要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
不允许使用sleep函数,不允许使用flag
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include <pthread.h>
#include<stdlib.h>
#include <string.h>
pthread_mutex_t mutex; //互斥锁
int *fdd2=NULL;
void* callBack1(void* arg)
{
int fd=*(int*)arg;
off_t size1=lseek(fd,0,SEEK_CUR);
off_t size=lseek(fd,0,SEEK_END);
int i=0;
char c;
lseek(fd,size1,SEEK_SET);
pthread_mutex_lock(&mutex); //上锁
for(i=0;i<size/2;i++)
{
if(read(fd,&c,1)<=0)
{
perror("read");
exit(0);
}
write(*fdd2,&c,1);
}
pthread_mutex_unlock(&mutex); //解锁
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
int fd=*(int*)arg;
off_t size1=lseek(fd,0,SEEK_CUR);
off_t size=lseek(fd,0,SEEK_END);
int i=0;
char c;
lseek(fd,size1,SEEK_SET);
pthread_mutex_lock(&mutex); //上锁
for(i=0;i<size/2;i++)
{
if(read(fd,&c,1)<=0)
{
perror("read");
exit(0);
}
write(*fdd2,&c,1);
}
pthread_mutex_unlock(&mutex); //解锁
}
int main(int argc, const char *argv[])
{
//创建互斥锁,并初始化
if(pthread_mutex_init(&mutex, NULL) != 0)
{
perror("pthread_mutex_init");
return -1;
}
printf("mutex_init success\n");
int fd=open("./1.png",O_RDONLY);
int fd2=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
fdd2=&fd2;
pthread_t tid1, tid2;
//创建一个线程,打印一半
if(pthread_create(&tid1, NULL, callBack1, &fd) != 0)
{
perror("pthread_create");
return -1;
}
//创建一个线程,打印另一半
if(pthread_create(&tid2, NULL, callBack2, &fd) != 0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
close(fd);
close(fd2);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}