Threading and locking
Date: 2/8/2004
I've been learning about some of the less obvious aspects of threaded code. Normally when you use threads to access common data you have a semaphore or mutex surrounding the resource so that only one thread can access the resource at any given time. Well thats the theory side of things. Seems fairly simple, you lock the resource, use it and then unlock it.

Well it isn't that simple (is it ever?). Due to the way locking is implemented in my own applications, one thread can hog the resource simply by locking and unlocking it too much. I have an example with 2 threads, the gui thread which is running the application's message loop wants to lock the resource once a second and the worker thread that is locking/unlocking the resource in a tight loop. The worker thread can always aquire the resource and the application thread can never acquire the resource. It seems if the period of time between the worker thread unlocking the resource and it relocking the resource is too small then no other thread has a chance to lock the resource.

Which in the case of Scribe means that the application's message loop locks up for up to 20 seconds. Which hangs the application... So I've been inserting sleeps into the worker thread code to leave air gaps for the application thread to aquire the resource and function properly.

This of course is a "hack" to make the application function, but in the long term the semaphore should be rewritten to play nicely. I'm not sure yet as to whether this is an artifact of my own implemenation of semaphores or it's an actual issue with semaphores in general. The other obvious thing is to reduce the amount of locking that the worker thread has to do. Which is an obvious gain in efficiency as well but would require more invasive changes to the code base than I really want to attempt while working on a stable release.

Speaking of which, Test18 hasn't received any reports of crashes or other nastyness. So I'm going to clean up a few cosmetic things for Test19 and release that as the new "Stable" build for Scribe. If you have any show stopper issues in Test18 please let me know.
03/09/2004 1:50pm
To stop starvation I'd suggest you have thread 1 (t1) ask thread 2 (t2) to go first before locking the mutex. If t2 says "No thanks, I'm not ready" then t1 uses the resource.

This way as soon as t2 is ready to do something, t1 asks and t2 says "Yes, I'm ready to do my thing now, thank you".

This pthread call will probably help.

Everybody plays nice and neither thread should starve for too long.
Email (optional): (Will be HTML encoded to evade harvesting)
Remember username and/or email in a cookie.
Notify me of new posts in this thread via email.