线程池原理及C语言实现线程池拷贝文件
时间: 2023-08-31 08:07:56 浏览: 111
基于C语言实现的线程池
线程池的原理已经在上面进行了解释,下面是一个使用线程池实现文件拷贝的C语言示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define THREAD_POOL_SIZE 5
#define BUFFER_SIZE 1024
typedef struct {
char src_file[256];
char dest_file[256];
} CopyTask;
typedef struct {
pthread_t thread;
int is_working;
} Worker;
CopyTask task_queue[THREAD_POOL_SIZE];
Worker workers[THREAD_POOL_SIZE];
pthread_mutex_t mutex;
pthread_cond_t cond;
void *worker_thread(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
// 等待任务到来
while (strlen(task_queue[*(int *)arg].src_file) == 0) {
pthread_cond_wait(&cond, &mutex);
}
// 执行任务
CopyTask copy_task = task_queue[*(int *)arg];
task_queue[*(int *)arg].src_file[0] = '\0'; // 清空任务
pthread_mutex_unlock(&mutex);
// 拷贝文件
FILE *src = fopen(copy_task.src_file, "rb");
FILE *dest = fopen(copy_task.dest_file, "wb");
if (src == NULL || dest == NULL) {
printf("Failed to open file.\n");
continue;
}
char buffer[BUFFER_SIZE];
size_t bytesRead;
while ((bytesRead = fread(buffer, sizeof(char), BUFFER_SIZE, src)) > 0) {
fwrite(buffer, sizeof(char), bytesRead, dest);
}
fclose(src);
fclose(dest);
printf("File copied from %s to %s\n", copy_task.src_file, copy_task.dest_file);
}
}
void thread_pool_init() {
int i;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
for (i = 0; i < THREAD_POOL_SIZE; i++) {
workers[i].is_working = 0;
task_queue[i].src_file[0] = '\0';
pthread_create(&workers[i].thread, NULL, worker_thread, &i);
}
}
void thread_pool_submit(char *src_file, char *dest_file) {
pthread_mutex_lock(&mutex);
// 查找空闲线程
int i;
for (i = 0; i < THREAD_POOL_SIZE; i++) {
if (strlen(task_queue[i].src_file) == 0) {
strcpy(task_queue[i].src_file, src_file);
strcpy(task_queue[i].dest_file, dest_file);
pthread_cond_signal(&cond);
break;
}
}
pthread_mutex_unlock(&mutex);
}
int main() {
int i;
thread_pool_init();
// 提交任务
for (i = 0; i < 10; i++) {
char src_file[256], dest_file[256];
sprintf(src_file, "source%d.txt", i);
sprintf(dest_file, "destination%d.txt", i);
thread_pool_submit(src_file, dest_file);
}
// 等待任务完成
sleep(1);
return 0;
}
```
在上述示例中,我们定义了一个 `CopyTask` 结构体,用于存储拷贝任务的源文件和目标文件。线程池中的任务队列存储了 `CopyTask` 结构体的实例。
在主函数中,我们初始化了线程池,并提交了10个文件拷贝任务。
阅读全文