I am trying to implement multithreading for a win 32 client/server application. Can anyone point out some resources in the net for learning Win32 multithreading, with examples if possible ?
You'll find that creating another thread is very easy (just call CreateThread).
The hard part is disciplining yourself not to access any variables that another thread might be accessing concurrently. That's a sure way to lose hair (as in: pulling it out by the handful). What happens is Thread A and B share a value, starting value of 4. A increments it by one. B then accesses it. B might see 4, or it might see 5, depending on the order in which things happened.
If you can make your secondary threads nearly independent from each other, you can use the parameter (4th argument to CreateThread) to pass in a structure containing all the variables it needs. Your thread can then work away without worrying about stomping on another thread's data.
You still need some way to indicate success or failure. You can use an integer with some constants like this:
#define NORESULT 0
#define RESULT_OK 1
#define RESULT_BAD 2
You can probably use an enum, as well. I like the constants, myself.
You would initialize the variable to NORESULT (meaning, you don't know if the thread's done yet). Then start the thread. Then check the variable every so often to see if the thread completed. It's perfectly safe to do this, as the main thread is simply watching the variable. The secondary thread is in control of setting it. If the main thread just misses seeing the variable being set, it's OK, as it'll pick it up next time it checks.
Another challenging area is telling threads it's time to stop (like when the app is ending). You *can* call ExitThread, but it's really rude and doesn't give you a chance to close files, etc. A better way would be to have a "StopAllThreads" boolean variable that all threads monitor to know when it's time to die. You can also use a semaphore (which is the technically correct way to do it), but a boolean works just as well.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.