quote:
Original post by amag
quote:
Using a non-kernel object (i.e. a regular variable) to signal for shutdown is faster than constantly calling WaitFor...()
Yes, so there must be a reason for using a kernel object now, mustn't it? I'd rather have a program that works than one really fast that doesn't.
Well, I used a normal variable in my example to signal a stop, not an event. My program still works. Why is that?
Multithreaded programming is difficult. A novice will attempt to solve any multithreading problem by either throwing more synchronization objects at the problem, or by using one synchronization object and acquiring it everywhere. This quickly turns nasty.
What you need to do instead is look at every piece of data that is shared between multiple threads, and ask yourself the question, "What happens if the value of this data changes after I've read it?" If something bad happens, you need to protect the data with a synchronization object.
In my example, the bool m_bStopThread is cleared before the thread stops. The thread will run until it reads the value of this flag as true. The only operation that can set this bool to false is the destructor. What happens in the destructor immediately after m_bStopThread is set? It waits on the thread handle.
So what happens if I set the m_bStopThread after the working thread has checked its value and read it as cleared? Well, my other thread is in an infinite wait on the thread handle. Therefore my worker thread gets all the CPU time, and finishes executing its loop before returning to the top and finding that the m_bStopThread flag is clear. It exits, setting the thread event and letting my original thread continue.
Obviously, there's no reason to make m_bStopThread an event. It only wastes a handle and causes undue context switching.
Now, if you're doing a Sleep within your worker thread, you're going to be switching contexts anyway. In this case, it can be handy (as I mentioned in my original post) to make the flag into an Event, and use the timeout in the WaitForSingleObject in place of your Sleep since they perform the same action. This also allows you to return instantly from the thread as soon as the event is signalled. But it's not a requirement in order for this thread scheme to work.
Edit - to fix nested quotes
Edited by - Stoffel on February 26, 2001 3:42:36 PM