2010-05-26 74 views
1

ThreadFunc()在这里被调用两次吗?有时我会注意到一个电话,有时甚至没有。在Win32中创建线程

#include <windows.h> 
#include <stdio.h> 

DWORD WINAPI ThreadFunc(LPVOID); 

int main() 
{ 
    HANDLE hThread; 
    DWORD threadld; 

    hThread = CreateThread(NULL, 0, ThreadFunc, 0, 0, &threadld); 
    printf("Thread is running\n"); 
} 

DWORD WINAPI ThreadFunc(LPVOID p) 
{ 
    printf("In ThreadFunc\n"); 
    return 0; 
} 

输出1

Thread is running 
In ThreadFunc 
In ThreadFunc 
Press any key to continue . . . 

输出2

Thread is running 
In ThreadFunc 
Press any key to continue . . . 

输出3

Thread is running 
Press any key to continue . . . 
+0

请点击此链接:http://stackoverflow.com/questions/601558/multithreading-reference – lsalamon 2010-05-26 19:28:25

回答

4

为了调用CRT功能,例如printf,您应该使用_beginthread_beginthreadex而不是CreateThread

无论如何,程序可能会在线程有机会输出任何内容之前结束。

2

稍微增加一点:在main()中使用WaitForSingleObject来为你的线程完成一项工作。

0

不,ThreadFunc不应该被调用两次。无论如何,我相信你的代码片段是不完整的 - 你能发布你看到这个问题的完整代码片段吗?