Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

program to print odd numbers and even numbers on seperate threads

Tags:

c

posix

I am learning programming using pthreads. How can I write a program to print odd numbers and even numbers on separate threads.

like image 652
user329013 Avatar asked Apr 30 '10 05:04

user329013


1 Answers

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.

like image 145
R Samuel Klatchko Avatar answered Nov 15 '22 07:11

R Samuel Klatchko