Nippysaurus Nippysaurus - 2 months ago 34
C Question

Multiple producer/consumer and critical section code problem

I am attempting a multiple producer/consumer problem in C, but its not working as expected. The following is some pseudo code to represent my implementation.

Thread thread1;
Thread thread2;
Thread thread3;

Data data1;
Mutex data1_mutex;
Semaphore data1_empty;
Semaphore data1_fill;

Data data2;
Mutex data2_mutex;
Semaphore data2_empty;
Semaphore data2_fill;

thread1()
{
// creates data and places it into data1.

wait(data1_empty);
lock(data1_mutex);

// critical section

unlock(data1_mutex);
post(data1_fill);
}

thread2()
{
// Removes data from data1, processes it, and places it into data2.

// data1
wait(data1_fill);
lock(data1_mutex);

// data2
wait(data2_empty);
lock(data2_mutex);

// critical section

// data2
unlock(data2_mutex);
post(data2_fill);

// data1
unlock(data1_mutex);
post(data1_empty);
}

thread3()
{
// Removes data from data2, prints its results, and removes it.

wait(data2_fill);
lock(data2_mutex);

// critical section

unlock(data2_mutex);
post(data2_empty);
}


However, with this solution data1 will fill up, but thread2 will lock and never run. Is there something wrong with my implementation?

EDIT #1

One of the problems I found was that my second mutex was not being created correctly. I don't know what's wrong with it so I'm just using the first mutex for all threads. There is also something else I have done to get it working, so I'll update my pseudo-code to reflect this later when I have a minute.

Answer

Make sure you post data1_empty and data2_empty initially.