Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Multithreading - optimizing return handling

So, I am currently writing a program that uses the standard pthread.h library. I want there to be multiple threads, all calculating stuff independently of each other at the same time (no mutexes needed). The main function needs to handle the return values of each thread (add them to an array/ linked list or something).

I could do something like this:

// the threads have already been created
data_type *data;            // assume this has been allocated properly etc
pthread_join(thread_id, (void *)data);
list_insert(head_of_list, data);

However, here is where my problem lies. From my understanding, when I repeat this in a loop for every thread, the code isn't optimized at all, because if every thread has finished running but the first, we would have to wait for the first to finish before recreating threads. Assuming a fixed amount of threads:

// still already initialized
for(int i=0; i<amount_of_threads; i++){
    data_type *data;        // assume this has been allocated etc properly
    pthread_join(array_of_thread_ids[i], (void *)data);
    list_insert(head_of_list, data);

    // create new thread with new job here
}

What I want the main function to do, is as soon as any of the threads finish running, do what is in the for loop for that specific thread and then continue waiting for the next one to finish. How can I solve this problem?

I have been rummaging around the internet but I have yet to find something that works efficiently. Surely I must be missing something.

Thank you in advance. Cheers

like image 919
Tritium Avatar asked Oct 23 '25 12:10

Tritium


1 Answers

I'd create a pool of workers, feed them work through a thread-aware queue, and collect the results using one as well.

like image 144
ikegami Avatar answered Oct 26 '25 16:10

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!