【问题标题】:C Pthreads Problem, Can't Pass the Info I Want?C Pthreads 问题,无法传递我想要的信息?
【发布时间】:2011-04-14 00:43:27
【问题描述】:

所以我试图让线程启动函数打开一个通过命令行提供的文件,每个线程一个文件,但我还需要启动函数来获取我的结果数组。所以基本上我需要一个字符串(文件名)和一个二维结果数组到我的启动线程中,我完全糊涂了。

有人有什么建议或想法吗?谢谢。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "string.h"


void* func(void *args);

int main(int argc, const char * argv[])
{
    int nthreads = 0;
    int i = 0;
    long **results;

    printf("Enter number of threads to use:\n> ");
    scanf("%d", nthreads);

    pthread_t threadArray[nthreads];

    // results 2d array; 3 rows by nthreads cols
    results = malloc((nthreads*4) * sizeof(long *));   

    for(i = 0; i<nthreads; i++) {
       pthread_create(&threadArray[i], NULL, wordcount, HELP!!!!); 
    } 

    for(i = 0; i<nthreads; i++) {
       pthread_join(threadArray[i], NULL);
    } 

    pthread_exit();
}

void * func(void *arguments)
{     
     FILE *infile = stdin;
     infile = fopen(filename, "rb");    

     fclose (infile);
}

【问题讨论】:

    标签: c arrays function pthreads startup


    【解决方案1】:

    通常声明和初始化包含线程数据的结构,并将指向该结构的指针作为线程参数传递。

    线程函数然后将void* 转换回结构指针并拥有数据。

    请记住,当线程被调度时,该结构的生命周期仍然有效(这意味着如果它是局部变量,则需要非常小心)。正如 Jonathan Leffler 指出的那样,传递每个线程它自己的结构实例,或者非常小心如何重用它。否则,如果结构在线程完成之前被重用,则线程可能会读取用于不同线程的数据。

    管理这些问题的最简单方法可能是为每个线程malloc() 一个结构,对其进行初始化,将指针传递给线程,并在处理完数据后让线程free() 它。

    【讨论】:

    • 有效且仍包含预期数据 - 您不能只为每个线程重用具有不同值的相同结构。
    【解决方案2】:

    pthread_create 的最后一个参数可以是你想要的任何对象,例如你可以有:

    struct ThreadArguments {
        const char* filename;
        // additional parameters
    };
    
    void* ThreadFunction(void* arg) {
        CHECK_NOTNULL(arg);
        ThreadArguments* thread_arg = (ThreadArguments*) arg;
        // now you can access the other parameters through this thread_arg object
        // ...
    }
    
    // ...
    ThreadArguments* arg = (ThreadArguments*) malloc(sizeof(ThreadArguments));
    ret = pthread_create(&thread_id, attributes, &ThreadFunction, arg);
    // make sure to check ret
    // ...
    pthread_join(thread_id);
    free(arg);
    

    【讨论】:

    • 我希望结果数组在线程之间共享,但最后线程函数会将该线程的结果放入二维数组中。如果为结构创建一个变量并仅更改文件名,那不会弄乱其他线程的文件名吗?
    • @Billy Reynolds - 您将为每个线程分配不同的结构实例。如果这是您想要的,这允许您传递给不同的文件名和相同的结果数组,只需将指针(或者您选择这样做)更改为每个实例的文件名字符串。 FWIW,如果您对线程不满意,那么传递相同的结果数组可能是个坏主意。很容易出错。最好将唯一的结果数组传递给每个线程,然后在 main(或任何产生线程的东西)中将它们组合起来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2016-08-05
    相关资源
    最近更新 更多