Multithreading: When to Start and Exit threads

∥☆過路亽.° 提交于 2020-01-25 00:15:11

问题


I am a little further along on this exercise and was not sure if I should post an answer with my updated code, edit my original post, or ask a new question. If I am not following protocol, please advise.

What I have done so far is read in the input file and assigned all the integers to an array. I then divided the total number of integers (index) by the number of threads (number_of_threads) to find the optimal numbers_per_thread.

I then create a while loop to increment through all the numbers in the array, assigning each block of numbers according to the optimal 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;
}

I am confused as to how I should handle the starting and stopping of threads. Should I start it inside of my for (j = 0; ..) loop and then create an if (j == numbers_per_thread) to end the thread? Should I create a new array to house the block of numbers for each thread? I guess I am just confused as to how to use pthread_create, pthread_join, etc. as this is my first time attempting to use them.


回答1:


I would make an array of pthread_t values to store the id of each thread you create. Create them in a loop after you've read the array of values, then immediately perform another loop to join them all. After that, you can take the individual partial sums and add them together to get your final sum.



来源:https://stackoverflow.com/questions/7438697/multithreading-when-to-start-and-exit-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!