• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Printing in order with c threads

Resolved: Printing in order with c threads

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

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:
Now, 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:
So far, nothing spectacular. The thread has now found all primes in its range and has come to the synchronizing part. The thread must
  • lock the mutex
  • wait for its turn (called “the predicate”)
  • let other threads do the same

Here’s one common pattern:
Now, the thread has reached the point where it is its time to print. It has the mutex lock so no other threads can reach this point at the same time.
And it can be tied together quite neatly in 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]

Demo

If you have better answer, please add a comment about this, thank you!

Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Resolved: Use Svelte Component as Slot

26/03/2023

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.