views:

134

answers:

1

Hello, 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 */

+3  A: 

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");
JonVD
This implementation is via a function? I have seen some minor code like: monitor network{/*code and conditions in here*/}. Was that pseudo code or is there keyword/data struct for monitors too?
Google
I've knocked out that monitor function I had and replaced it with a more direct answer. If you'd like that code back just let me know, I just re-read your question and saw that it wasn't quite what you were asking. In your above comment that code that your referring to is pseudo code, to the best of my knowledge that construct doesn't exist in C.
JonVD
Thanks, I think I will try to implement mine via a function with semaphores in main and try to use it to monitor various threads. I need to read more on the topic, it's quite complex.
Google
I agree, it is very complex! Many a headache and seg_fault has been hit working out these sorts of problems, that link I posted above helped me a lot. If you have any further questions just post it up.
JonVD