Timers and events with multithreading

BlitzMax Forums/BlitzMax Programming/Timers and events with multithreading

elcoo(Posted 2011) [#1]
Hi,
is it even possible to use timers or events in a second thread, created using CreateThread()? Because when I create a timer inside the Thread and use WaitTimer(), the thread will just halt and never go on, as if the Timer wasn't ticking. Same is for WaitEvent.


ima747(Posted 2011) [#2]
Not sure about how timers are structured, but I assume they are not thread safe. They likely are bound to the main thread, not the calling thread.

Events are definitely NOT thread safe. Events are pulled from, and push to a que, and that que is not handled in a thread safe manner. (even if you wrapped your polling commands to be thread safe when events are created they are not inserted safely so you could still "cross the beams").

It is possible to post events (and one could extrapolate polling as well) from a thread, but you have to wrap the action in a main thread handling routine. e.g.

Child thread wants to post an event. So it creates the event and, in a thread safe manner shoves it into a tlist.

The main loop every cycle examins the tlist (again in a thread safe manner) and if it finds anything it posts the event.

I use this method in one of my applications, however you have to let the main loop cycle and poll events yourself rather than waiting on them. OR you have to be confident that something will trigger you waitevent to process (such as moving the mouse) which gives you an opportunity to post those other events. This is preferable from a resources standpoint (much less processor time spent cycling) but obviously until one event happens, allowing the child created events to get posted, then they don't exist.


ima747(Posted 2011) [#3]
There are other ways to do triggered sharing as well, such as with semaphores, but this becomes a LOT harder, especially with the poor documentation for semaphores and condvars etc.


elcoo(Posted 2011) [#4]
Hi ima747,
thanks for the replies, it made things a bit clearer for me. I didn't find any good documentation about semaphores and mutexes yet. I'll try around a bit now to find out which is the best method to synchronize and run Threads at the same speed.


ima747(Posted 2011) [#5]
Check out my guide in the tutorials section for getting your feet wet in multithreading. It's quite powerful but prone to catastrophic failure if you're not very careful :0)