Reputation: 346
I am trying to make a test console application which opens and downloads data from different COM ports using different threads . After downloading data I am using WaitForMutipleObjects() to wait for download to complete from all the threads.
WaitForMultipleObjects(nThreadCount,m_threadHandle,true,INFINITE);
But this is not working , thread is returning without being executed . Here is my thread function.
void* Test::GetData(void *p)
{
Test *pThis = (Test *)p;
string strCOMport;
int nChannelNo,nBaudRate;
cout<< " Enter COM port "<<endl;
cin>>strCOMport;
cout<< " Enter Channel Number"<<endl;
cin>>nChannelNo;
cout<< " Enter Baud Rate "<<endl;
cin>>nBaudRate;
if(pThis->InitPort(nChannelNo,0x00,(unsigned char *)strCOMport.c_str(),nBaudRate,0x00) == 0x00)
cout<< "Init port Success"<<endl;
else
{
cout<< "failed";
return NULL;
}
// download
ExitThread(0);
}
These are the functions which are creating and Waiting for threads respectively
void Test::init()
{
m_threadHandle[nThreadCount] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)GetData,(LPVOID)this,0,&m_dwThreadID[nThreadCount]);
nThreadCount++;
}
void Test::WaitForThreads()
{
WaitForMultipleObjects(nThreadCount,m_threadHandle,true,INFINITE);
}
Why is the thread function returning abruptly?
Upvotes: 0
Views: 312
Reputation: 612954
Your thread procedure has the wrong signature. Note that you used a cast to make your code compile. Your code probably originally said:
CreateThread(..., GetData, ...);
And the compiler objected to GetData
saying that it was not compatible with a parameter of type LPTHREAD_START_ROUTINE
. Unfortunately you chose the wrong solution. Casting it to LPTHREAD_START_ROUTINE
does not actually make GetData
be a LPTHREAD_START_ROUTINE
. It just shuts the compiler up.
CreateThread(..., (LPTHREAD_START_ROUTINE)GetData, ...);
Here, GetData
is still not a LPTHREAD_START_ROUTINE
, but now the compiler is not able to save you from yourself.
So, you need to declare GetData
to have the correct signature.
DWORD WINAPI GetData(LPVOID lpParameter);
And this must be a non-member function, or a static member function.
Once you fix all this you will find that you no longer need to call ExitThread()
. You can simply write return 0
from your thread function.
Upvotes: 3