互斥锁
定义一个全局变量,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<unistd.h>
#include<string.h>
//线程A,B
//A循环打印
//B循环倒置
//A顺序打印
char str[]="123456";
pthread_mutex_t mutex;
void *callbaskA(void *arg)
{
while(1)
{
// pthread_mutex_lock(&mutex); //上锁
printf("%s\n",str);
//sleep(1);
// pthread_mutex_unlock(&mutex);
//解锁
}
//退出线程
pthread_exit(NULL);
}
void *callbaskB(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[])
{
printf("程序运行\n");//全局变量,局部变量访问
pthread_t tid1,tid2;
//买锁
/* if(pthread_mutex_init(&mutex,NULL)!=0)
{
perror("pthread_mutex_init");
return -1;
}*/
if(pthread_create(&tid1,NULL,callbaskA,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,callbaskB,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
//销毁锁
pthread_mutex_destroy(&mutex);
//阻塞
return 0;
}
拷贝图片
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int fd_r,fd_w;
off_t size;
pthread_mutex_t mutex;
void *fore(void *arg)
{
pthread_mutex_lock(&mutex); //上锁
//修改文件偏移量到开头位置
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
//读一次写一次,直到size/2
int i = 0;
char c;
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 *later(void * arg)
{
pthread_mutex_lock(&mutex); //上锁
//便宜到size/2的位置
lseek(fd_r, size/2, SEEK_SET);
lseek(fd_w, size/2, SEEK_SET);
//读一次写一次,直到size/2
int i = 0;
char c;
for(i=size/2; i<size; i++)
{
if(read(fd_r, &c, 1) <= 0)
{
perror("read");
// return -1;
}
write(fd_w, &c, 1);
}
pthread_mutex_unlock(&mutex);
//退出线程
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
printf("程序运行\n");//全局变量,局部变量访问
pthread_t tid1,tid2;
//买锁
if(pthread_mutex_init(&mutex,NULL)!=0)
{
perror("pthread_mutex_init");
return -1;
}
//以读的方式打开源文件
fd_r = open(argv[1], O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
//以写的方式打开目标文件
fd_w = open("copy.png", O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
//计算文件大小
size = lseek(fd_r, 0, SEEK_END);
if(pthread_create(&tid1,NULL,fore,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,later,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
//销毁锁
pthread_mutex_destroy(&mutex);
return 0;
}