Frosted Cupcake
Frosted Cupcake

Reputation: 1970

Using Pthread library in C

I have this code:

#include<stdio.h>
#include<pthread.h>

int mutex=1,i=0,full=0;

void p(int *s)
{
    while(*s<=0)

    ;

    *s--;
}

void v(int *s)
{
    *s++;
}

void *producer()
{
    p(&mutex);
    printf("Producer is producing\n");
    v(&mutex);
    v(&full);
}

void *consumer()
{
    p(&full);
    p(&mutex);
    printf("Consuming\n");
    v(&mutex);
}

int main()
{
    pthread_t thread1,thread2;
    int k;

    for(k=0;k<10;k++)
    {       
        pthread_create(&thread1,NULL,(void *(*)(void *))producer,NULL);
        pthread_create(&thread2,NULL,(void *(*)(void *))consumer,NULL);
    }

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
}

Before adding p(&full) in consumer function, this code was working fine, randomly selecting one out of two functions every time; but after adding p(&full) in consumer() function, every time it is executing producer() function. I don't understand the reason for this.

Can someone please help me,and suggest possible solution for this problem? I want that first time producer function should execute.

Upvotes: 1

Views: 1115

Answers (2)

gby
gby

Reputation: 15218

The code is broken in too many ways to understand what is going on. These two issues pop to mind.

  1. i-- and i++ are not atomic operations, so the neither mutex or full has the values you think they do.

  2. You are creating 20 threads but only joining on the last two.

  3. You have no memory barriers in the code so that order of how changes to memory in an SMP system is practically undefined.

Upvotes: 0

Clifford
Clifford

Reputation: 93476

Inter-thread synchronisation via shared variables is almost certainly a bad idea, but even so the shared variables should at least be declared volatile.

Consider using real synchronisation primitives such as semaphores or real Pthreads mutexes.

Your use of the term mutex here is incorrect; it is not a mutex. A mutex should be locked and released in the same thread and is intended to prevent other threads accessing a resource. If that is not the behaviour hat you want then a mutex is the wrong primitive - perhaps you need a semaphore rather than a mutex.

Upvotes: 2

Related Questions