Using threads in C on Windows. Simple Example?

szaman picture szaman · Dec 30, 2009 · Viewed 52.5k times · Source

What do I need and how can I use threads in C on Windows Vista?

Could you please give me a simple code example?

Answer

i_am_jorf picture i_am_jorf · Dec 30, 2009

Here is the MSDN sample on how to use CreateThread() on Windows.

The basic idea is you call CreateThread() and pass it a pointer to your thread function, which is what will be run on the target thread once it is created.

The simplest code to do it is:

#include <windows.h>

DWORD WINAPI ThreadFunc(void* data) {
  // Do stuff.  This will be the first function called on the new thread.
  // When this function returns, the thread goes away.  See MSDN for more details.
  return 0;
}

int main() {
  HANDLE thread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
  if (thread) {
    // Optionally do stuff, such as wait on the thread.
  }
}

You also have the option of calling SHCreateThread()—same basic idea but will do some shell-type initialization for you if you ask it, such as initializing COM, etc.