1.使用线程实现文件分两部分拷贝
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <pthread.h>
int cp;
int vp;
int flag;
size_t size;
void *up(void *arg)
{
char buf[200] = {0};
pthread_mutex_lock((pthread_mutex_t*)arg);
lseek(cp, 0, SEEK_SET);
lseek(vp, 0, SEEK_SET);
for (size_t i = 0; i < size / 2+flag; i++) // 父进程复制上半截,某些地方没必要判断
{
read(cp, buf, 1);
write(vp, buf, 1);
memset(buf, 0, sizeof(buf));
}
pthread_mutex_unlock((pthread_mutex_t*)arg);
}
void *down(void *arg)
{
char buf[200] = {0};
pthread_mutex_lock((pthread_mutex_t*)arg);
lseek(cp, size / 2, SEEK_SET);
lseek(vp, size / 2, SEEK_SET);
for (size_t i = 0; i < size / 2 + flag; i++)
{
memset(buf, 0, sizeof(buf));
if (read(cp, buf, 1) < 0)
{
perror("read");
break;
}
write(vp, buf, 1);
}
pthread_mutex_unlock((pthread_mutex_t*)arg);
}
int main(void)
{
cp = open("1.jpeg", O_RDONLY);
vp = open("2.jpeg", O_WRONLY | O_CREAT | O_TRUNC, 0777);
if (cp < 0)
{
perror("open cp");
return -1;
}
if (vp < 0)
{
perror("open vp");
return -1;
}
size = lseek(cp, 0, SEEK_END);
if (size % 2 == 0) // 解决文件大小奇偶性对半问题
flag = 0;
else
flag = 1;
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_t tid1, tid2;
int res1 = pthread_create(&tid1, NULL, up, (void*)&mutex);
int res2 = pthread_create(&tid2, NULL, down, (void*)&mutex);
if (res1 != 0 || res2 != 0)
{
printf("线程创建失败\n");
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
close(cp);
close(vp);
return 0;
}
2线程无名信号量实现倒置循环打印字符串
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
sem_t sem;
sem_t sem2;
char buf[] = "1234567";
void* callback1(void* arg)
{
while(1)
{
sem_wait(&sem);
printf("%s\n",buf);
//sleep(1);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void* callback2(void *arg)
{
int len = strlen(buf);
char temp;
int j;
while(1)
{
sem_wait(&sem2);
for(int i =0,j = len-1;i<j;i++,j--)
{
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
//sleep(1);
sem_post(&sem);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem,0,1);
sem_init(&sem2,0,0);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,callback1,NULL);
pthread_create(&tid2,NULL,callback2,NULL);
pthread_detach(tid2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem);
return 0;
}