How can I code a monitor in C? How can I code a monitor in C? unix unix

How can I code a monitor in C?


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 excusion. 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 some read as to how and when to use each of them as that is a little long to cover here, 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");


The above code to init the semaphore and mutex is great. Here is an example of how to use it in a program that could have errors when multi-threaded.

struct account{        int balance;        int finished;        pthread_mutex_t mutex;        pthread_cond_t deposit; };static void init_account(struct account *act){        act->balance = 0;        act->finished = 0;        pthread_mutex_init(&act->mutex,NULL);        pthread_cond_init(&act->deposit,NULL);}static void deposit(struct account *act, int amount){        pthread_mutex_lock(&act->mutex);        fprintf(stderr, "Deposit:%d\n",amount);        act->balance += amount;        pthread_cond_broadcast(&act->deposit);        pthread_mutex_unlock(&act->mutex);}