22

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

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

4

3 回答 3

37

这是有关如何在 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.
  }
}

您还可以选择调用SHCreateThread() — 基本思想相同,但如果您提出要求,它会为您执行一些 shell 类型的初始化,例如初始化 COM 等。

于 2009-12-30T17:50:39.707 回答
3

您将使用CreateThread函数。

你也提到了信号量。为此,您将使用CreateSemaphore

于 2009-12-30T17:51:41.277 回答
1

原子操作和互斥锁很好。我使用 CreateThread 等,而不是 pthreads。

于 2009-12-30T17:57:35.277 回答