开发者

Multithreading: When to Start and Exit threads

开发者 https://www.devze.com 2023-04-05 10:00 出处:网络
I am a little further along on this exercise and was not sure if I should post an answer with开发者_如何学Python my updated code, edit my original post, or ask a new question. If I am not following pr

I am a little further along on this exercise and was not sure if I should post an answer with开发者_如何学Python 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号