thread synchronization for two threads using one semaphore
<p>I want to synchronize threads to print from 1 to 20 with odd numbers printed by thread1 and even numbers printed by thread2</p>

<p>I achieved this with two semaphores.</p>

<p>Questions:</p>

<p>1) Can this be achieved using only one semaphore ?</p>

<p>2) Is there any efficient way to achieve this ?</p>

<p>If possible please provide example too.</p>

<pre><code>sem_t bin_sem1, bin_sem2;
int count = 1;

int main()
{
    int ret;
    pthread_t a_thread, b_thread;

    ret = sem_init(&amp;bin_sem1, 0, 1);
    if (ret != 0)
    {
        perror("semaphore1 initialization failed\n");
        exit(EXIT_FAILURE);
    }
    ret = sem_init(&amp;bin_sem2, 0, 0);
    if (ret != 0)
    {
        perror("semaphore2 initialization failed\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_create(&amp;a_thread, NULL, thread_fun1, NULL);
    if (ret != 0)
    {
        perror("Thread1 creation failed");
        exit(EXIT_FAILURE);
    }

    ret = pthread_create(&amp;b_thread, NULL, thread_fun2, NULL);
    if (ret != 0)
    {
        perror("Thread2 creation failed");
        exit(EXIT_FAILURE);
    }

    printf("Waiting for threads to finish\n");
    ret = pthread_join(a_thread, NULL);
    if (ret != 0)
    {
        perror("Thread1 join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread1 joined");

    ret = pthread_join(b_thread, NULL);
    if (ret != 0)
    {
        perror("Thread2 join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread2 joined");

    exit(EXIT_SUCCESS);
}

void *thread_fun1(void *arg)
{
    int val=0, val2=0;
    while (count &lt; 20)
    {
        sem_wait(&amp;bin_sem1);
        sem_getvalue(&amp;bin_sem1, &amp;val);sem_getvalue(&amp;bin_sem2, &amp;val2);
        printf("T 1 : after wait  : sem 1 = %d, sem 2 = %d\n", val, val2);

        printf("T 1 : count = %d\n", count++);

        sem_post(&amp;bin_sem2);
        sem_getvalue(&amp;bin_sem1, &amp;val);sem_getvalue(&amp;bin_sem2, &amp;val2);
        printf("T 1 : after post  : sem 1 = %d, sem 2 = %d\n", val, val2);
    }
    pthread_exit(NULL);
}
void *thread_fun2(void *arg)
{
    int val=0, val2=0;
    while (count &lt; 20)
    {
        sem_wait(&amp;bin_sem2);
        sem_getvalue(&amp;bin_sem1, &amp;val);sem_getvalue(&amp;bin_sem2, &amp;val2);
        printf("\t\t\t\t\t\tT 2 : after wait  : sem 1 = %d, sem 2 = %d\n", val, val2);

        printf("\t\t\t\t\t\tT 2 : count = %d\n", count++);

        sem_post(&amp;bin_sem1);
        sem_getvalue(&amp;bin_sem1, &amp;val);sem_getvalue(&amp;bin_sem2, &amp;val2);
        printf("\t\t\t\t\t\tT 2 : after post  : sem 1 = %d, sem 2 = %d\n", val, val2);
    }
    pthread_exit(NULL);
}
</code></pre>