#include "head.h"
void* callback(void* arg)
{
int fd, fd1, len;
pthread_t sid;
char c=0;
if ((fd = open("./jpg.jpg", O_RDONLY)) < 0)
{
perror("fail to open");
exit(-1);
}
if ((fd1 = open("./jpg1.jpg", O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
{
perror("fail to open");
exit(-1);
}
len = lseek(fd, 0, SEEK_END);
len /= 2;
while(1)
{
lseek(fd,0,SEEK_SET);
lseek(fd1,0,SEEK_SET);
for(int i=0;i<len;i++)
{
read(fd,&c,1);
write(fd1,&c,1);
}
sleep(1);
}
pthread_exit(NULL);
return NULL;
}
int main(int argc, char *argv[])
{
int fd, fd1, len;
pthread_t sid;
char c=0;
if ((fd = open("./jpg.jpg", O_RDONLY)) < 0)
{
perror("fail to open");
exit(-1);
}
if ((fd1 = open("./jpg1.jpg", O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
{
perror("fail to open");
exit(-1);
}
len = lseek(fd, 0, SEEK_END);
while(1)
{
lseek(fd,0,SEEK_SET);
lseek(fd1,0,SEEK_SET);
for(int i=0;i<len;i++)
{
read(fd,&c,1);
write(fd1,&c,1);
}
sleep(1);
}
if(pthread_create(&sid,NULL,callback,NULL)!=0)
{
fprintf(stderr, "failed __%d__\n",__LINE__);
return -1;
}
pthread_join(sid,NULL);
return 0;
}
#include "head.h"
char buf[]="1234567";
// A线程打印buf字符串的函数
void* printfBuf(void* arg) {
while (1)
{
// 判断buf是否等于"1234567",如果不等于则等待条件变量发出信号
while((strcmp(buf, "1234567") != 0)||(strcmp(buf,"7654321") != 0))
{
printf("%s\n", buf);//打印字符串
}
}
return NULL;
}
// B线程倒置buf字符串的函数
void* circulate(void* arg) {
while (1)
{
// 判断buf是否等于"7654321",如果不等于则等待条件变量发出信号
while((strcmp(buf, "7654321") != 0) || (strcmp(buf,"1234567") != 0))
{
int len = strlen(buf);//倒置buf字符串
for (int i = 0; i < len / 2; i++)
{
char temp = buf[i];
buf[i] = buf[len - i - 1];
buf[len - i - 1] = temp;
};
}
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t printBuf, reverseBuf;
// 创建打印线程
if(pthread_create(&printBuf, NULL, printfBuf, NULL) != 0)
{
fprintf(stderr,"printBuf failed __%d__\n",__LINE__);
return -1;
}
// 创建倒置线程
if(pthread_create(&reverseBuf, NULL, circulate, NULL) != 0)
{
fprintf(stderr,"reverseBuf failed __%d__\n",__LINE__);
return -1;
}
// 等待线程结束
pthread_join(printBuf, NULL);
pthread_join(reverseBuf, NULL);
return 0;
}