I need to do some process synchronization in C. I want to use a monitor, and I have read a lot about them. However I have been unable to find out how to implement one in C. I have seen them done in Java and other languages like C++, but I am unable to find examples in C.
I have looked through K&R and there is no example in there. I skimmed through Unix Systems Programming, Communication, Concurrency and Threads, but was unable to find a monitor implementation in there.
This brings me here. Where and how do I define a monitor? How do I implement it within the rest of the code?
/* I am coding in a *nix environment */
I did this recently for a project, the concept I implemented was to have one thread start all of the others and then use semaphores and mutexes to control the inter process sync issues while dealing with shared memory.
The concept of a monitor, in the context of the monitor design pattern, is a construct that is basically there to hide mutual exclusion. This concept is expressed in C++ Boost but it doesn't exist in core C++ or C. The way you handle this type of job in C is with good old fashioned mutexes (binary semaphores) and semaphores. You can read more about this here.
Below is a basic way to initialize a semaphore and mutex, you may need to do more research of your own, but here is a link to get you started.
pthread_mutex_t myMutex;
sem_t mySemaphore;
int status;
status = pthread_mutex_init(&myMutex, NULL);
if(status != 0)
exit_with_error("There was an Error Initalizing the Mutex\n");
status = sem_init(&mySemaphore, 0, 0);
if(status != 0)
printf("There was an Error Initalizing the Semaphore\n");