【发布时间】:2011-01-26 09:08:47
【问题描述】:
我正在使用 _beginthreadex 在 c 中创建一个新线程。我已经编写了以下代码。 相同的代码用两个版本编写,第一个版本可以正常工作,但第二个版本不工作。
工作代码
main.c
#include <windows.h>
#include <stdio.h>
extern void func(unsigned (__stdcall *SecondThreadFunc)( void* ));
int main()
{
func(NULL);
}
秒.c
#include<Windows.h>
//when thread start routine is declared in the same file new thread is running fine...
//but if this routine is moved to main.c and passed as parameter to func new thread is not working
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n ");
return 0;
}
void func(unsigned (__stdcall *SecondThreadFunc)( void* ))
{
HANDLE hThread;
printf( "Creating second thread...\n" );
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, NULL );
// Wait until second thread terminates.
WaitForSingleObject( hThread, INFINITE );
}
代码无效(如下)
main.c
#include <windows.h>
#include <stdio.h>
#include <process.h>
extern void func(unsigned (__stdcall *SecondThreadFunc)( void* ));
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n ");
return 0;
}
int main()
{
func(SecondThreadFunc);
}
秒.c
#include<Windows.h>
void func(unsigned (__stdcall *SecondThreadFunc)( void* ))
{
HANDLE hThread;
printf( "Creating second thread...\n" );
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, NULL );
// Wait until second thread terminates.
WaitForSingleObject( hThread, INFINITE );
}
在调用 SecondThreadFunc 时,我在 _beginthreadex 中遇到访问冲突。有人能帮帮我吗。提前致谢。
【问题讨论】:
-
printf() 等 stdio 函数不是线程安全的。
标签: c multithreading winapi