I am trying to create a basic thread from main by passing a function to _beginthread. But My output is not getting completed.
I am getting the following output:
Starting thread
48
Main ends
I
Could someone please clarify what is wrong in the following code?
#include <iostream>
#include <process.h>
using namespace std;
void test(void *param)
{
cout << "In thread function" << endl;
Sleep(1000); // sleep for 1 second
cout << "Thread function ends" << endl;
_endthread();
}
int main()
{
cout << "Starting thread" << endl;
cout << _beginthread(test,0,NULL);
cout << "Main ends" << endl;
return 0;
}
Because return from the main will stop any threads in your application. You need to wait untill thread will stop. Simplest solution with global var - very bad example to be honest. You need to use wait functions on thread's handle.
#include <iostream>
#include <process.h>
using namespace std;
bool threadFinished = false;
void test(void *param)
{
cout << "In thread function" << endl;
Sleep(1000); // sleep for 1 second
cout << "Thread function ends" << endl;
threadFinished = true;
_endthread();
}
int main()
{
cout << "Starting thread" << endl;
cout << _beginthread(test,0,NULL);
while(!threadFinished)
{
Sleep(10);
}
cout << "Main ends" << endl;
return 0;
}
How to use Wait functions:
HANDLE hThread;
hThread = (HANDLE)_beginthread( test, 0, NULL);
WaitForSingleObject( hThread, INFINITE );