The documentation is a bit scattered, so here's what I found useful:
- Multithreading with C++ and MFC
- CWinThread Class
- AfxBeginThread
- WaitForSingleObject Function
- WaitForMultipleObjects Function
If you are comfortable with the concept of threads, and you're just looking to find the language constructs to make them, here's the short of it:
If you want a thread that will make GUI elements to interact with the user, you'll want to check out Multithreading: Creating User-Interface Threads, but otherwise, it's quite simple.
Write a non-member function — it could be a regular function, or a static function of a class object, but it cannot be a "method"/instance function (sorry, I'm probably mixing up Java terminology here).
Then use AfxBeginThread to "spin" off a thread that wraps around the function you just wrote. It'll execute your function on a thread. There are options that allow you to make sure the thread object thus created does not auto-delete — you'll have to flag AfxBeginThread to not auto start the thread though, then use ResumeThread to start the thread after you've set m_bAutoDelete.
You don't want the thread object to auto-delete once the function it wraps around is done executing because you might want to keep tabs on the thread. You might want to block execution until the thread(s) are done executing. You can do this blocking with the WaitFor*Object(s) functions (documentation linked at top as well).
If the thread auto-deletes, the WaitFor* function can explode while trying to check if the thread is done executing.
You can throw off multiple threads wrapping around the same function. If the function interacts with the outside world, you'll have to keep track of any synchronization issues yourself though.
No comments:
Post a Comment