在Windows上使用C中的线程.简单的例子?

sza*_*man 20 c windows multithreading semaphore

我需要什么以及如何在Windows Vista上使用C语言中的线程?

你能给我一个简单的代码示例吗?

i_a*_*orf 33

以下是有关如何在Windows上使用CreateThread()的MSDN示例.

基本思想是调用CreateThread()并向其传递一个指向线程函数的指针,该函数在创建后将在目标线程上运行.

最简单的代码是:

#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.
  }
}
Run Code Online (Sandbox Code Playgroud)

你也可以选择调用SHCreateThread() -相同的基本想法,但是如果你问的话,会为你做一些shell类型的初始化,比如初始化COM等.

  • 但请记住,如果您要在新线程中使用CRT,您可能需要非常小心.例如,在MSVC中,您应该使用_beginthread/_beginthreadex和_endthread而不是相关API,让CRT正确地分配/释放其内部每线程结构.我认为在其他CRT中也应该以某种方式. (3认同)