【问题标题】:Multithreading: When to Start and Exit threads多线程:何时启动和退出线程
【发布时间】:2011-09-15 23:45:02
【问题描述】:

我在this exercise 上走得更远一点,不确定是否应该使用更新的代码发布答案、编辑原始帖子或提出新问题。如果我不遵守协议,请告知。

到目前为止,我所做的是在输入文件中读取并将所有整数分配给一个数组。然后,我将整数总数 (index) 除以线程数 (number_of_threads) 以找到最佳 numbers_per_thread

然后我创建一个while循环来递增数组中的所有数字,根据最佳numbers_per_thread分配每个数字块。

prob_5.c

#include <stdio.h>

int main(int argc, char *argv[]) {
int i, j;
FILE *fp;
int values[15000];
char line[32];
int index = 0;
int number_of_threads = 10;
int numbers_per_thread;

for (i = 1; i < argc; i++) {
    fp = fopen(argv[i], "r");

    if (fp == NULL) {
        fprintf(stderr, "cat: can't open %s\n", argv[i]);
        continue;
    }

    while (fgets(line, sizeof(line), fp) != NULL && (index < 15000)) {
        sscanf(line, "%d", &values[index]);
        index++;
    }

    fclose(fp);
}

numbers_per_thread = index / number_of_threads;

while (i < index) {
    for (j = 0; (j < numbers_per_thread) && (i < index); j++) {

        i++;
        j++;
    }
}

printf("%d\n", index);

return 0;
}

我对如何处理线程的启动和停止感到困惑。我应该在我的 for (j = 0; ..) 循环中启动它,然后创建一个 if (j == numbers_per_thread) 来结束线程吗?我应该创建一个新数组来容纳每个线程的数字块吗?我想我只是对如何使用 pthread_create、pthread_join 等感到困惑,因为这是我第一次尝试使用它们。

【问题讨论】:

    标签: c multithreading pthreads


    【解决方案1】:

    我会创建一个 pthread_t 值数组来存储您创建的每个线程的 id。读取值数组后,在循环中创建它们,然后立即执行另一个循环以将它们全部连接起来。之后,您可以将各个部分的总和相加得到最终总和。

    【讨论】:

    • 感谢您的建议。我添加了 pthread_t 线程[number_of_threads] 并创建了这个 for 循环: for (i = 0; i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多