C语言写一个双线程的文件复制程序
时间: 2024-10-11 20:11:18 浏览: 53
c语言 线程复制文件 or 文件夹
在C语言中编写一个多线程文件复制程序涉及到`pthread.h`库,这是一个处理线程的头文件。下面是一个简单的示例,它创建两个线程分别负责读取源文件和写入目标文件:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <pthread.h>
#define BUFFER_SIZE 4096
#define SRC_FILE "source.txt"
#define DST_FILE "destination.txt"
void* read_thread(void *arg) {
FILE *src = fopen(SRC_FILE, "rb");
char buffer[BUFFER_SIZE];
int bytes;
while ((bytes = fread(buffer, sizeof(char), BUFFER_SIZE, src)) > 0) {
pthread_mutex_lock(&mutex);
fwrite(buffer, bytes, 1, dst);
pthread_mutex_unlock(&mutex);
}
fclose(src);
return NULL;
}
void* write_thread(void *arg) {
FILE *dst = fopen(DST_FILE, "wb");
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 初始化和解锁是多余的,这里是示例,实际上不需要这样做
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex); // 确保先获取锁
read_thread(NULL); // 调用另一个线程
pthread_mutex_destroy(&mutex);
fclose(dst);
return NULL;
}
int main() {
pthread_t reader_thread, writer_thread;
if (pthread_create(&reader_thread, NULL, read_thread, NULL) != 0) {
perror("Error creating reader thread");
exit(1);
}
if (pthread_create(&writer_thread, NULL, write_thread, NULL) != 0) {
perror("Error creating writer thread");
exit(1);
}
pthread_join(reader_thread, NULL);
pthread_join(writer_thread, NULL);
printf("File copy completed.\n");
return 0;
}
阅读全文