1.定义一个全局变量,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>
#include <stdlib.h>
#include <unistd.h>
char str[]="123456";
pthread_mutex_t mutex;
//打印
void *dayin(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
printf("%s\n",str);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
//倒置
void *daozhi(void *arg)
{
int len=strlen(str);
char temp;
while(1)
{
pthread_mutex_lock(&mutex);
for(int i=0;i<len/2;i++)
{
temp=str[i];str[i]=str[len-i-1];str[len-i-1]=temp;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex,NULL);
pthread_t tid1;
if(pthread_create(&tid1,NULL,dayin,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_t tid2;
if(pthread_create(&tid2,NULL,daozhi,NULL)!=0)
{
perror("pthread_create");
return -1;
}
while(1)
{
sleep(1);
}
pthread_mutex_destroy(&mutex);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
2. 要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
不允许使用sleep函数,不允许使用flag
#include<stdio.h>
#include<pthread.h>
#include <unistd.h>
FILE * fp;
FILE * op;
pthread_mutex_t mutex;
//前半部分
void *front(void * arg)
{
char s;
fseek(fp,0,SEEK_END);
int size=ftell(fp);
for(int i=0;i<=size/2;i++)
{
//上锁
pthread_mutex_lock(&mutex);
fseek(fp,i,SEEK_SET);
fread(&s,1,1,fp);
fseek(op,i,SEEK_SET);
fwrite(&s,1,1,op);
//解锁
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
//后半部分
void *tail(void *arg)
{
char s;
fseek(fp,0,SEEK_END);
int size=ftell(fp);
for(int i=size/2;i<size;i++)
{
//上锁
pthread_mutex_lock(&mutex);
fseek(fp,i,SEEK_SET);
fread(&s,1,1,fp);
fseek(op,i,SEEK_SET);
fwrite(&s,1,1,op);
//解锁
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
//主函数
int main(int argc, const char *argv[])
{
fp=fopen(argv[1],"r");
op=fopen(argv[2],"w");
if(NULL==fp)
{
perror("fopen");
return -1;
}
if(NULL==op)
{
perror("fopen");
return -1;
}
fseek(fp,0,SEEK_SET);
if(pthread_mutex_init(&mutex,NULL)!=0)
{
perror("pthread_mutex_init");
return -1;
}
pthread_t td;
if(pthread_create(&td,NULL,front,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_t pd;
if(pthread_create(&pd,NULL,tail,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(td,NULL);
pthread_join(pd,NULL);
pthread_mutex_destroy(&mutex);
fclose(fp);
fclose(op);
return 0;
}