Using threads in C on Windows. Simple Example? [cl

2019-01-16 17:36发布

问题:

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

Could you please give me a simple code example?

回答1:

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.



回答2:

You would use the CreateThread function.

You mentioned semaphores as well. For that you would use CreateSemaphore.



回答3:

Atomic operations and mutexes are good. I use CreateThread etc, not pthreads.