请提供并发下载文件的C#例子
时间: 2023-02-23 09:16:52 浏览: 74
下面是一个实现并发下载文件的C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#define BUFSIZE 1024
#define MAX_THREAD 4
struct download_task {
char url[BUFSIZE];
char filename[BUFSIZE];
};
void* download_routine(void* arg) {
struct download_task *task = (struct download_task*)arg;
char cmd[BUFSIZE];
sprintf(cmd, "wget %s -O %s", task->url, task->filename);
system(cmd);
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("Usage: %s [file_list] [output_dir]\n", argv[0]);
return -1;
}
FILE* fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("fopen");
return -1;
}
char line[BUFSIZE];
struct download_task tasks[MAX_THREAD];
pthread_t threads[MAX_THREAD];
int task_cnt = 0;
while (fgets(line, BUFSIZE, fp) != NULL) {
line[strlen(line) - 1] = '\0';
sprintf(tasks[task_cnt].url, "%s", line);
sprintf(tasks[task_cnt].filename, "%s/%d", argv[2], task_cnt);
pthread_create(&threads[task_cnt], NULL, download_routine, &tasks[task_cnt]);
task_cnt ++;
if (task_cnt == MAX_THREAD) {
for (int i = 0; i < MAX_THREAD; i ++) {
pthread_join(threads[i], NULL);
}
task_cnt = 0;
}
}
fclose(fp);
for (int i = 0; i < task_cnt; i ++) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
该代码实现了从文件中读取下载任务,每次启动最多 4 个线程并发下载文件,下载完成后等待所有线程结束。使用方法是:在第一个参数指定文件列表文件,