Reputation: 4716
I am creating a new thread in c using _beginthreadex. I have written the following code. same code written in two versions, first version is working properly but second one is not working.
working code
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 );
}
Not working code(Below)
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 );
}
I am getting access violation inside _beginthreadex while calling SecondThreadFunc. Can some help me out. Thanks in advance.
Upvotes: 0
Views: 723
Reputation: 30301
In the not working code you should have (pay attention to the &s):
hThread = (HANDLE)_beginthreadex( NULL, 0, SecondThreadFunc, NULL, 0, NULL );
Upvotes: 1