I am learning programming using pthreads. How can I write a program to print odd numbers and even numbers on separate threads.
You need two synchronization objects such as a semaphore or a condition variable. The idea is that thread A requests semaphore A before it prints and releases semaphore B after while thread B does the opposite.
The idea is that after thread A requests semaphore A, it will drop the semaphore to 0. The next time it requests semaphore A it will block until thread B releases the semaphore.
In pseudo code, this looks like:
initialization:
// set semA to 1 so that the call to sem_wait in the
// even thread will succeed right away
sem_init(semA, 1)
sem_init(semB, 0)
even_thread:
to_print = 0;
loop:
sem_wait(semA);
write(to_print);
to_print += 2
sem_post(semB)
odd_thread:
to_print = 1
loop:
sem_wait(semB)
write(to_print)
to_print += 2
sem_post(semA)
Since you want to teach yourself threads programming, I'll leave it to you to convert this into actual pthreads code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With