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.
How to use Wait functions: