Writing Your First Thread Function

[Previous] [Next]

Every thread must have an entry-point function where it begins execution. We already discussed this entry-point function for your primary thread: main, wmain, WinMain, or wWinMain. If you want to create a secondary thread in your process, it must also have an entry-point function, which should look something like this:

 DWORD WINAPI ThreadFunc(PVOID pvParam){ DWORD dwResult = 0;.     return(dwResult); } 

Your thread function can perform any task you want it to. Ultimately, your thread function will come to an end and return. At this point, your thread stops running, the memory for its stack is freed, and the usage count of your thread's kernel object is decremented. If the usage count becomes 0, the thread kernel object is destroyed. Like process kernel objects, thread kernel objects always live at least as long as the thread they are associated with, but the object might live well beyond the lifetime of the thread itself.

Let me point out a few things about thread functions:

  • Unlike a primary thread's entry-point function, which must be named main, wmain, WinMain, or wWinMain, a thread function can have any name. In fact, if you have multiple thread functions in your application, you have to give them different names or the compiler/linker will think that you've created multiple implementations for a single function.
  • Because your primary thread's entry-point function is passed string parameters, ANSI/Unicode versions of the entry-point functions are available: main/wmain and WinMain/wWinMain. Thread functions are passed a single parameter whose meaning is defined by you, not the operating system. Therefore, you do not have to worry about ANSI/Unicode issues.
  • Your thread function must return a value, which becomes the thread's exit code. This is analogous to the C/C++ run-time library's policy of making your primary thread's exit code your process's exit code.
  • Your thread function (and really all your functions) should try to use function parameters and local variables as much as possible. When you use static and global variables, multiple threads can access the variables at the same time, potentially corrupting the variables' contents. However, parameters and local variables are created on the thread's stack and are therefore far less likely to be corrupted by another thread.

Now that you know how to implement a thread function, let's talk about how to actually get the operating system to create a thread that executes your thread function.



Programming Applications for Microsoft Windows
Programming Applications for Microsoft Windows (Microsoft Programming Series)
ISBN: 1572319968
EAN: 2147483647
Year: 1999
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net