Click to See Complete Forum and Search --> : cannot creat multithread with _beginthread


love2mao
April 2nd, 2004, 02:46 PM
#include "stdafx.h"
#include <windows.h>
#include <winbase.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <process.h>

void __cdecl threadWork(void* in)
{
printf("test");
_endthread();
}

int main(int argc, char* argv[])
{
printf("Hello World!\n");
unsigned long ret = _beginthread(threadWork, 0, 0);
return 0;
}

But looks like thread proc doesn't run at all. I check the return value. It's positive. Just wonder why thread is not running. Thank you.:eek:

Mick
April 2nd, 2004, 02:51 PM
The main thread is ending before the created thread gets a slice to execute. Put a sleep behind your _beginthread() or use a sync object to wait on.

wayside
April 2nd, 2004, 02:53 PM
Well, you immediately exit the program after creating the thread. When would it have to run?

Put in a Sleep(1000) after you create the thread and before you return from main, then you should see the thread run.

Also, you don't need to explicitly call endthread() in your thread, it will happen automagically when you return from your thread function.

love2mao
April 2nd, 2004, 02:58 PM
So valuable help for me :)

Andreas Masur
April 2nd, 2004, 03:37 PM
[Moved thread]

IsaacTheIceMan
October 15th, 2004, 06:41 AM
here is some code slightly modified from what I found in MSDN. The code provides a more reliable method of waiting for a thread to finish using WaitForSingleObject(). However, you need to strore the HANDLE to the thread when it is created

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <process.h>

unsigned Counter;
void __cdecl SecondThreadFunc( void* pArguments )
{
printf( "second thread\n" );
}

int main()
{
HANDLE hThread;
unsigned threadID;

printf( "Creating second thread...\n" );

// Create the second thread.
hThread = (HANDLE)_beginthread(&SecondThreadFunc, 0, NULL);

// Wait until second thread terminates. If you comment out the line
// below, the second thread will have no chance to finish
WaitForSingleObject( hThread, INFINITE );

// Destroy the thread object.
CloseHandle( hThread );
}