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

二次信任 提交于 2019-11-27 00:23:29

问题


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.



来源:https://stackoverflow.com/questions/1981459/using-threads-in-c-on-windows-simple-example

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