Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Win32 Multithreading

Status
Not open for further replies.

abp

Programmer
Sep 14, 2000
134
FR
Hi all,

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 ?

Thanks

abp
 
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.

Hope this helps.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top