6

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;
}
TechyHarry
  • 301
  • 2
  • 8
  • 25

3 Answers3

10

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 );
kuperspb
  • 339
  • 2
  • 10
  • Thanks for quick response. But what if I need to create a child process that doesn't depend on parent? I mean parent can exit but child can still run. – TechyHarry Oct 25 '12 at 06:44
  • @kuperspb, access to variable threadFinished is not synchronized, also, why you are using while-sleep loop, if wait functions are already exists in windows? – rkosegi Oct 25 '12 at 06:48
  • @kuperspb: Fantastic explanation :). Thanks a lot. This is what exactly I am searching for. – TechyHarry Oct 25 '12 at 06:49
  • As i said in my answer - it's just to show where is a problem lies. For this example - there is no problem with access to global var without sync. And using of wait functions show lower in my answer. – kuperspb Oct 25 '12 at 06:51
  • @kuperspb One more query, If I try to create threads from a dll and don't call WaitForSingleObject, my threads are not getting killed even after dll completes its task. My dll is still loaded. Could you please explain is there anything wrong in doing that or should I need to really wait? – TechyHarry Oct 26 '12 at 05:26
  • Using dll is fine. Dll can be unloaded manually by FreeLibrary call, or on exit from the program. But with dll you have another problem - you need to control memory very carefully. Using delete operator inside exe module for memory, allocated inside dll and vice versa will cause error and app will crash. Best solution - using shared_ptr from standart library (C++11). – kuperspb Oct 26 '12 at 05:50
3

You can use CreateThread method.

Simple example of multithreading.

#include <Windows.h>
#include <iostream>

using namespace std; 

DWORD WINAPI thread1(__in LPVOID lpParameter) {
    while (1) {
        std::cout << " From Thread 1 \n";
        Sleep(3000);
    }

}

DWORD WINAPI thread2(__in LPVOID lpParameter) {
    while (1) {
        std::cout << " From thread 2\n"; 
        Sleep(1000);

    }
}

int main()
{

    DWORD threadID1, threadID2; 
    HANDLE h1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread1, 0, 0,&threadID1);
    HANDLE h2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread2, 0, 0, &threadID2);

    getchar();
    return 0;
}

where thread 1 prints for every 3 secs and thread2 prints for every sec.

You can allocate stack size if your process is bigger.

StackSize explanation

Wickkiey
  • 4,446
  • 2
  • 39
  • 46
2

You need to wait for thread to end using some synchronization primitives, or your program will call ExitProcess before thread finished his execution.

You may read about synchronization first to understand how to write multithreaded application.In your case you need single object wait functions.

See msdn example: http://msdn.microsoft.com/en-us/library/kdzttdcb%28v=vs.71%29.aspx

so, you main function should look something like this :

int main()
{
    HANDLE hThread;
    cout << "Starting thread" << endl;
    cout << (hThread = (HANDLE)_beginthread(test,0,NULL));
    WaitForSingleObject( hThread, INFINITE );
    cout << "Main ends" << endl;
    return 0;
}
rkosegi
  • 14,165
  • 5
  • 50
  • 83
  • Thanks for quick response. But what if I need to create a child process that doesn't depend on parent? I mean parent can exit but child can still run. – TechyHarry Oct 25 '12 at 06:45
  • 1
    @HareeshSarma this sounds like POSIX fork.If parent is main process's thread your whole process (including worker threads) will die as well.So you need to spawn other child process or NOT EXIT from main thread. – rkosegi Oct 25 '12 at 06:47
  • One more query, If I try to create threads from a dll and don't call WaitForSingleObject, my threads are not getting killed even after dll completes its task. My dll is still loaded. Could you please explain is there anything wrong in doing that or should I need to really wait? – TechyHarry Oct 26 '12 at 05:26