Question:
Given this code:whos_turn
will here be used to tell the threads whos turn it is to print the primes found.Each thread also needs some thread-unique information. You called it
val
so I’ll call it val
here too. We can compare val
with whos_turn
to decide which thread it is that should print its result. In order to pass both the shared data and val
to a thread, you can package that in a struct
too:findPrimes
need somewhere to store the primes it calculates before it’s time to print them. Since the range to search is hardcoded, I’d just add an array for that:- lock the mutex
- wait for its turn (called “the predicate”)
- let other threads do the same
Here’s one common pattern:
main
:#define Size(x) (sizeof (x) / sizeof *(x))
int main() {
shared_data sd = {.whos_turn = 0,
.mtx = PTHREAD_MUTEX_INITIALIZER,
.cv = PTHREAD_COND_INITIALIZER};
pthread_t p[3];
work_order wos[Size(p)];
for (unsigned i = 0; i < Size(p); i++) { wos[i].val = i; // the thread-unique information wos[i].sd = &sd; // all threads will point at the same `shared_data` pthread_create(&p[i], NULL, findPrimes, &wos[i]); } for (unsigned i = 0; i < Size(p); i++) { pthread_join(p[i], NULL); } } [/code]
DemoIf you have better answer, please add a comment about this, thank you!