The impurity of semaphores

May sound more like a general rant about misunderstanding thread synchronizations, but it isn't like that. Well, I thought creating a tasker system would remove all the need to write more thread code, but it turned out that I forget to implement a method of waiting for a task to finish. This is especially important for my ressource loader thread system that enables to enlist for preloading (in case of, for example, NPCs close to you which may play certain sounds on certain events which aren't immediately required) or requiring a certain ressource right now. The latter screams for a mutex object to be unlocked when done with loading, but it'd need to get locked by another thread - which's impossible because this thread is responsible to executing tasks and can't immediately lock the mutex for himself, creating a useless lock/unlock combination in the thread waiting for a task to be done. I knew I'd need either double mutex locking or a free combination or locking/unlocking for one thread from another. Double locking did not work on my Linux system, thus rendering it useless for my situation. I had atleast 3 different "solutions" which all based on so special threading implementation details that I couldn't have a guarantee for them to work as expected. Wicked! Absolutely. So I asked one of my lecturers and he mentioned that this problem could be solved using a semaphore. So me didn't first understood why, but then it hit me like nothing did for a while. I learned semaphores as suitable for accessing ressources by a limited number of different threads. Therefore having a number to up/down, an access mutex and so on. However, when all slots got filled, SDL offers me the possibility to wait on the semaphore to become free - exactly what makes it possible to "lock" a one-slot semaphore by the thread posting tasks and then trying to wait for it to become avaible. The thread would wait until someone would increment the value as done by the tasker when executing the task. All provided that SDL allows me to increment the semaphore value multiple time on any major system - it's the only possible way to avoid polling of availability.

That said, I'm only using a side-effect coming through the way a semaphore functions. I find it... impure. Impure in the way of knowing exactly what but prevented by the library/system used caused no finer thread control is necessary. I mean I like standardized functionality, but using a not so suited synchronization object's side-effects is not what I'd want to find in a clean engine. Well, my scripting language will possibly differ from the currently used technology I think. Anyway, I prefer message-based systems more than synchronization system. It's simply more of what I usually use when programming games.

No comments: