Multithreading: when to start and display streams

I was a little further on this exercise and was not sure that I should post an answer with my updated code, edit the original post, or ask a new question. If I do not follow the protocol, please let us know.

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

Then I create a while loop to increment 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 about how I should work with starting and stopping threads. Should I run it inside the for loop (j = 0; ..) and then create if (j == numbers_per_thread) to end the thread? Should I create a new array to place a block of numbers for each stream? I guess I'm just confused about how to use pthread_create, pthread_join etc., since this is the first time I'm trying to use them.

+1
source share
1 answer

I would make an array of pthread_t values ​​to store the identifier of each thread being created. Create them in a loop after you read an array of values, then immediately run another loop to join them. After that, you can take individual partial amounts and add them together to get the final amount.

0
source

All Articles