I have been reading about difference between binary semaphore and mutex and reading below link mutex vs binary semaphore it says "Mutex can be released only by thread that had acquired it, while you can signal semaphore from any other thread (or process), so semaphores are more suitable for some synchronization problems like producer-consumer"
however in below example I am locking mutex in one thread and releasing it in another thread. Have I mis-understood the statement from the link presented or I have wrong understanding of my own implementation ? Again I was just poking around the code to have more better understanding of things and I was not expecting things to work but to my surprise it works fine.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#define WORKERS 2
#define ARRAY_ELEMENTS 100
#define MAX 1000
pthread_mutex_t arraynotfull = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t access_array = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t arraynotempty = PTHREAD_MUTEX_INITIALIZER;
bool available = false;
void *worker_thread(void *pbucket)
{
while(1)
{
unsigned int count = 0;
int local_array[ARRAY_ELEMENTS];
int *ptbucket = (int*)pbucket;
setbuf(stdout, NULL);
pthread_mutex_lock(&arraynotempty);
pthread_mutex_lock(&access_array);
while(count < ARRAY_ELEMENTS)
{
local_array[count] = ptbucket[count];
count++;
}
pthread_mutex_unlock(&access_array);
pthread_mutex_unlock(&arraynotfull); //unlocking in consumer
count = 0;
while(count < ARRAY_ELEMENTS)
{
printf(" %d - \n", local_array[count]);
count++;
}
}
}
int main(void)
{
pthread_t thread_id[WORKERS];
unsigned int* pbucket1 = (int*) malloc(sizeof(int) * ARRAY_ELEMENTS);
unsigned int* pbucket = pbucket1;
for(int i = 0; i < WORKERS - 1; i++)
{
pthread_create(&thread_id[i], NULL, worker_thread, (void *) pbucket);
}
for(int i = 0; i < MAX; i++)
{
unsigned int count = 0;
// Make the payload ready
pthread_mutex_lock(&arraynotfull); // locking in producer
pthread_mutex_lock(&access_array);
while(count < ARRAY_ELEMENTS)
{
pbucket1[count] = i;
i++;
count++;
}
pthread_mutex_unlock(&access_array);
pthread_mutex_unlock(&arraynotempty);
}
for(int i = 0; i < WORKERS; i++)
{
pthread_join(thread_id[i], NULL);
}
return 0;
}