tags:

views:

527

answers:

2

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

+1  A: 

Pass an indicator value to indicate if the thread should be printing odd number or even number through the thread function argument.

Depending upon the same, start from 0 (for even numbers) or 1 (for odd numbers) and keep incrementing by 2 in both the threads and print.

You can also print the thread-id along with the number to indicate which thread is printing what.

I assume you know how to use pthreads.

[Update]: Link for pthreads Even with the use of semaphores or mutex, it is difficult for you to get the output in order of 1,2,3 etc as you never know which thread will get the chance to execute first. For this, you may have to use some advanced concepts like thread priority or Inter-thread communication using conditional variables. These are just hints. I hope if you go through the link you will get more information.

Jay
I am learning pthreads..The solution i was looking for was thread synchronization using semaphores.The output should be 1,2,3.....But odd numbers and even numbers should be printed on separate threads.It would be helpful if anyone can provide the details of usage.Also any link to study pthreads.
+2  A: 

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.

R Samuel Klatchko
+1. This answer is good. It totally skipped my mind. : )
Jay
+1 for teaching to fish :)
Tim Post