我正在使用_beginthreadex在c中创建一个新线程。我写了以下代码。 相同的代码用两个版本编写,第一个版本正常工作但第二个版本无效。
工作代码
的main.c
#include <windows.h>
#include <stdio.h>
extern void func(unsigned (__stdcall *SecondThreadFunc)( void* ));
int main()
{
func(NULL);
}
second.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);
}
second.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中遇到访问冲突。有人可以帮助我。提前谢谢。
答案 0 :(得分:1)
在你不应该使用的代码中(注意&amp; s):
hThread = (HANDLE)_beginthreadex( NULL, 0, SecondThreadFunc, NULL, 0, NULL );