习惯于linux C 语言编程,忽然转到Windows平台有很多不习惯,在Windows创建一个线程本是很简单的一个事,网上的资料介绍的却是各种复杂,最后还是谷歌搜索到MSDN官方资料,上面有个很简单的例子,它与linux 创建线程类似。
// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>
unsigned Counter;
unsigned __stdcall SecondThreadFunc(void* pArguments)
{
printf("In second thread...\n");
while (Counter < 1000000)
Counter++;
_endthreadex(0);
return 0;
}
int main()
{
HANDLE hThread;
unsigned threadID;
printf("Creating second thread...\n");
// Create the second thread.
hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &threadID);
// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject(hThread, INFINITE);
printf("Counter should be 1000000; it is-> %d\n", Counter);
// Destroy the thread object.
CloseHandle(hThread);
}
在main 函数里,使用_beginthreadex 函数创建一个线程,该线程执行函数SecondThreadFunc。WaitForSingleObject 函数功能主要是阻塞main主线程的执行,直到SecondThreadFunc 线程执行结束main主线程才继续往下执行。
详细内容见MSDN _beginthread, _beginthreadex