When confronted with a segfault, it almost always is a dereference of some bogus value. When interpreted as an address, it is very unlikely that such a value points into a valid segment.
There are two causes for these segfaults in your program:
- You initialize each thread with an 'ID = list + 1', which means the numbers 1 trough 5. You address the 'flag' array directly using this id. Array indices start at zero, not at one! This means you will never use flag[0], and dereference a value beyond the array bounds whenever monitor 5 is trying to eat.
- Check your #define for the RIGHT macro, shouldn't the condition be (ID == 4) instead of (ID == ID-1)? This might also trigger a dereference of some bogus value beyond the 'flag' array bounds.
Additionally:
- Joining the thread xyz[list] will cause problems. Because 'list' has just been iterated in a loop it will actually contain the value 5 (the first value that fails the loop conditional). You are now calling pthread_join(xyz[5], NULL), which is beyond the bounds of xyz. This will cause very odd behavior, most likely that main simply doesn't wait for any of the threads to finish and exits immediately. Instead, use:
pthread_join(xyz[0], NULL);
- You must join all threads, not just the first one. In this case, since neither of the threads will ever stop, it is not a problem. In general, unless you specifically want the program to exit with running threads, use:
for(list = 0; list<5; list++) pthread_join(xyz[list], NULL);
- See the answer given by John H.
The code runs fine after these fixes:
http://pastebin.com/hgk7C280 (EDIT: fixed the malloc(1) issue, see the answer given by John H)
Only problem now is that the appetite of these monitors is enormous, and they just keep on thinking and eating and the program never stops. You should probably make them count down the number of times they eat.