Using threads in C on Windows. Simple Example? [closed]

左心房为你撑大大i 提交于 2019-11-28 04:34:32

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.

You would use the CreateThread function.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!