1.定义一个全局变量,char str[] = “123456”,要求定义两个线程:线程A, 线程B
-
要求A线程循环打印全局字符串str;
-
要求B线程循环倒置全局字符串str:将str中的内容倒置为"654321",再倒置为"123456"…
注意:是倒置不是倒着打印
-
要求A线程打印出的str字符串内容为:123456或者654321。
不允许出现乱序,例如:623451 653451,,,
#include <stdio.h>
#include <pthread.h>
#include <string.h>
char str[] = "123456";
pthread_mutex_t mutex;
void* callBack_print(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
printf("%s\n", str);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* callBack_reserve(void* arg)
{
int i = 0;
char temp = 0;
while(1)
{
pthread_mutex_lock(&mutex);
for(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);
}
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");
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, callBack_print, NULL) != 0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2, NULL, callBack_reserve, NULL) != 0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
- 要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
不允许使用sleep函数,不允许使用flag
#include<pthread.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
pthread_mutex_t mutex;
int fd_r,fd_w;
off_t size;
void* A(void* arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
int i;
char c;
lseek(fd_r,0,SEEK_SET);
lseek(fd_w,0,SEEK_SET);
for(i=0;i<size/2;i++)
{
if(read(fd_r, &c, 1) <= 0)
{
perror("read");
}
write(fd_w, &c, 1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void* B(void* arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
int i;
char c;
lseek(fd_r,size/2,SEEK_SET);
lseek(fd_w,size/2,SEEK_SET);
for(i=size/2;i<size;i++)
{
if(read(fd_r, &c, 1) <= 0)
{
perror("read");
}
write(fd_w, &c, 1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
fd_r=open("./2.png",O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
fd_w= open("./copy.png",O_RDWR|O_TRUNC|O_CREAT,07770);
if(fd_w < 0)
{
perror("open");
return -1;
}
size = lseek(fd_r, 0, SEEK_END);
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,A,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,B,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}