Sunday, September 26, 2010

Threading and Mutexes

So the overall assignment this week was more or less the same as last week, make your main/parent program call a thread to do the fibbonacci work. That was easy, so easy I did it at 3am friday morning when I couldn't sleep, in about 30 minutes, it took a little bit of rework from the fork program I wrote last week, but was simple to implement.

This morning I was thinking about mutex's.  I know that you use a mutex as a semaphore of sorts in that when you've locked it other processes needing to use it (or really use some variable you're about to modify) won't be able to.

So what I did was lock it in the child thread, then when the sibling thread attempts to lock it, it can't, and then forces it to wait until it's unlocked once the child unlocks then the sibling can print the elements of the shared memory.

Remember to include pthreads, you simply have to #include
then to compile it would be gcc -pthread -o filename.o

Good luck!

Here are a few screen shots of the results.
Fibonacci Threaded

Fibonacci with Mutexes