How do I get started working with threads?

Threads are really not that difficult, and worker threads
in particular are quite easy (worker threads don't have a user
interface, they just do work in the background). MFC isn't
really threadsafe, and rather than spend time remembering what
I can and can't do with MFC and threads, I just avoid the use
of MFC within threads: my C++ apps tend to have an MFC core with
pure C/SDK worker threads.

Essentially a worker thread consists of a function, which is
specified when the thread is created (using CreateThread for an
SDK program, or AfxBeginThread for an MFC program). When the
function exits, the thread is done. CreateThread looks complex,
but most of its parameters can be left at the defaults.

The only mildly tricky part is ensuring that the threads get
killed off if your app is closed down: this usually requires that
your main thread set an "event" (see CreateEvent/SetEvent)
which the worker(s) can check - if it/they see the event set they
drop out of their processing loop, exit and therefore cease.

Of course if you want multiple threads accessing a single
resource (such as a data structure), you'll need to read up on
synchronisation using Critical Section objects. Actually getting
to the shared object is trivial, as threads share the same address
space. Think of it like this : processes are the unit of
addressability ; threads are the unit of executability.

Check out these fragments of code, which are from a
multithreaded application I wrote some time ago. The application
creates a closure event thus :

So you can see that the code is setting up a table of
structures with data about each thread, then calling AfxBeginThread
to create the thread, passing it the address of the structure which
contains information it will need internally, such as the handle of
the application closure event. The thread has no problem accessing
this structure, because all threads share the same address space. The
application's main thread then saves a pointer to the worker thread,
which it can use when shutting down to ensure that all threads close
when instructed using the closure event: if any threads fails to
shutdown before some timeout, the app can call TerminateThread to
forcibly kill it.

The worker thread run function looks like this (note the
thread-local variables, which contain data specific to this thread):

Get the picture ? Our thread basically consists of a
loop, which sleeps until either a character is received or the
app closure event gets set by the main thread. So how does the
main thread organise closure of its kiddies ? Like this :