使用线程并发下载文件

标签 c multithreading concurrency

您好,我在并发下载和发送文件时遇到一些问题。这是我的代码:

在 main() 中

while(1){
    while(i < wrapper->request_get->maxconnect && nconn < 5){
         wrapper->request_get->temp = i;
         i++;nconn++;
         if((pth=pthread_create(&id[i],NULL,thread_func,wrapper))!=0){
         ...
         ...
      }

所以我需要一次下载一个最多有 5 个连接的通用文件。变量“i”和“nconn”是全局变量,从值 0 开始。

在thread_func()中:

    void *thread_func(void* args){
    pthread_mutex_lock(&mutex);
    j++;//it's global set to -1
    struct RequestWrapper *wr = args;
    ...
    ...//I set the range of data to request.
    ...//for example,thread #1 needs bytes from 1 to 100;#2 from 101 to 200 etc...
    ...//I do that with the value of "j".

    handlerRequest(wr)//this function asks(using a connect) to server a file's single part and save it
                      //into a buffer of struct wr.

    if(array[j]!=1){//if is not it my turn to send, wait
           pthread_cond_wait(&cond, &mutex);}

    SendData(wr)//send data conteined into a buffer of wr.
    array[j+1]=1;//I enable the next thread to send
    pthread_mutex_unlock(&mutex);
    pthread_cond_broadcast(&cond);//unlock other threads
nconn--;
pthread_exit(NULL);                 
}

不幸的是,通过这种方式我可以顺序下载和发送数据。

thread#1 download---send---thread#2 download---send---etc etc

如何同时下载五部分文件并在准备好后立即有序发送?我是线程方面的新手,所以我认为一些未知的,对我来说,函数可以帮助我,但哪些?ps:我不能使用信号...

最佳答案

好吧,我假设 http 部分工作正常,服务器可以接受多个请求,并且支持 from-to 部分。现在只要进入你的线程,我就看到你持有一个互斥对象:o。这本身使得整个操作是连续的(一次一个 handlerRequest),因为一次只有一个线程正在执行,这是您不想要的。整 block 代码不需要线程安全,你说呢?

您需要创建 5 个线程,其中有 5 个线程对象等待,我不知道在 Linux 中用于此目的的是什么,但在 Windows 中您将使用 WaitForMultipleObjects,也许检查一下:

WaitForSingleObject and WaitForMultipleObjects equivalent in linux

通常,当要分部分下载文件时,您向服务器请求文件大小,在磁盘上分配返回长度的文件,从不同位置开始打开多个文件指针(在您的情况下为 5),每个线程将使用其各自的文件指针写入该文件。一旦 5 个互斥体(或任何正确的线程对象)被释放,它将表明 5 个线程已完成工作,然后 SendData 可以执行其操作。

我希望我没有完全错,呵呵:)

关于使用线程并发下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9027793/

相关文章:

c - 在函数调用期间避免 sizeof 样板的宏函数

java - 类变量以外的对象的易变性

java - wait() 和 sleep() 有问题吗?

python - 如何使用 asyncio 同时运行无限循环?

c - 带有 "%d"以 0 开头的数字(例如 "0102")的 printf 给出意外的答案(例如 '"66")

捕获从命令行返回的空输出,如果为空则显示一些消息

c - C 中的 "dimension"和 "parameter"等效命令

c# - 填充同一 DataSet 的不同 DataTable 是线程安全操作吗?

java - 乐观锁 - Hibernate 的并发问题

c# - .NET 4.0 System.Collections.Concurrent 集合在 .NET 3.0 SynchronizedCollection 的功能中添加了什么?