【问题标题】:Concurrent Threads and global variables并发线程和全局变量
【发布时间】:2016-02-11 22:46:26
【问题描述】:

我有一个处理文件的函数。在我的主要方法中,我有一个循环来创建(文件数)子线程,并同时处理它们。我必须有一个特定的输出,例如输出需要与调用的文件完全一样,所以如果我的程序用“a.out file1 file2 file3”调用,输出需要是“输出文件1,输出文件2,输出文件 3"。

现在,它以错误的顺序输出文件,显然是因为某些线程先完成。

我的代码如下所示:

char *output[10];

void *file_thread(void *arg)
{
    //processing the file
    // I need to write to output here.
}

int main (int argc, char **argv)
{
    int e;
    int status;
    pthread_t thread[argc - 1];
    // For each file    
    for (e = 1; e < argc; e++)
    {
        status = pthread_create(&thread[e-1], NULL, file_thread,     
                (char     *)argv[e]);
        if (status != 0)
        {
            err_abort(status, "pthread create");
        }
    }



    for (e=0; e < argc - 1; e++)
    {
        pthread_join(thread[e], NULL);
    }
    /*
    for(e=0; e < argc - 1; e++)
    {
        printf("%s", output[e]);
    }
    */
    return 0;
}

所以我需要做的是在 main 方法中以某种方式跟踪每个线程的变量 e。我不允许使用管道。我尝试创建一个不同的全局变量 x ,在创建线程之前/之后的每次迭代中将其分配给 e ,但在 thread_file 中,它始终输出 x 作为最终迭代的值。

基本上,我需要根据文件编号将变量 e 存储为不同的值。然后,在main方法的最后,我就可以按顺序打印了。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: c multithreading


    【解决方案1】:

    最简单的解决方案是使向量数组全局化(使其更具动态性,或者以过度杀伤的大小...)然后让每个线程等待前一个完成(线程 n 调用线程 n 上的 join -1,除了线程 0) 在吐出它的输出之前。

    希望他们在开始读取输入时不会立即开始输出内容...或者您必须缓存它,然后等待前一个完成后再写入该缓存。

    HTH

    【讨论】:

      【解决方案2】:

      我让它工作了。我在每次迭代中使用了一个带有变量 e 的结构。然后我将它传递给我的 thread_create。

      成功了!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        • 2013-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多