Running pthreads at the same time

What are the different ways to ensure that a group runs simultaneously pthreads?

I could find only one way, i.e. initializing barrierin the main thread and then waiting for it in the newly created pthreads.

+3
source share
2 answers

This is pretty much accurate as I did in the past.

main:
    claim mutex
    for each desired thread:
        start child
    release mutex
    :

child:
    claim mutex
    release mutex
    :

Please note that this does not actually guarantee that all threads are started before the first one starts to do something, just created the main thread.

To do this, you can use something like the following method:

main:
    claim mutex
    set unstarted to 0
    for each desired thread:
        start child
        add 1 to unstarted
    release mutex
    :

child:
    claim mutex
    subtract 1 from unstarted
    while unstarted > 0:
        release mutex
        yield // if necessary
        claim mutex
    release mutex
    :

, , , claim subtract.


, . pthread, , .

, , - pre-v6 pthreads ( ), , , , .

+6

pthread_cond_broadcast. - . , undefined.

#include <pthread.h>

pthread_mutex_t join_mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void thread_function (void *param) {
    pthread_mutex_lock(&join_mut);
    pthread_cond_wait(&cond, &join_mut);
    pthread_mutex_unlock(&join_mut); 

    /* Thread work here */
}

enum { threads = 16 };

int main() {
  int i;
  pthread_t thread_table[threads];

  for(i = 0; i < threads; i++) {
    pthread_create(&(thread_table[i]), NULL, thread_function, NULL);
  }

  /* Wait for all threads to be queued */

  pthread_cond_broadcast(&cond);
}
0

Source: https://habr.com/ru/post/1770053/


All Articles