Why the thread can not be created?

J

Jack

Hi,

In the code below:

#include <process.h>

unsigned __stdcall ReadThread( void *arg )
{
while( 1 )
{
cout << "RUN" << endl;
}
_endthreadex( 0 );
return 0;
}

int main( int argc, char **argv )
{

.......

HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &ReadThread, NULL, 0,
&threadID ); //LINE1
if (hThread == 0) {
cout << "Failure in _beginthreadex(), errno: " << endl;
}

}

Why at LINE1, hThread is always 0, i.e., the thread is not created?

I use Visual Studio .NET 2003.

Thanks.

Jack
 
D

Doug Harrison [MVP]

Hi,

In the code below:

#include <process.h>

unsigned __stdcall ReadThread( void *arg )
{
while( 1 )
{
cout << "RUN" << endl;
}
_endthreadex( 0 );
return 0;
}

int main( int argc, char **argv )
{

.......

HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &ReadThread, NULL, 0,
&threadID ); //LINE1
if (hThread == 0) {
cout << "Failure in _beginthreadex(), errno: " << endl;
}

}

Why at LINE1, hThread is always 0, i.e., the thread is not created?

I use Visual Studio .NET 2003.

Thanks.

Jack

When I:

1. Add the following to the top:

#include <windows.h>
#include <iostream>
using namespace std;

2. Delete the "......." line.

3. Compile with cl -EHsc -MD a.cpp.

The output is "RUN" in VC 2003. BTW, there's rarely any reason to use
_endthreadex. Simply returning from the thread function accomplishes the
same thing. Also, you shouldn't allow your secondary threads to continue
running while the main thread is shutting down the process and destroying
the environment in which the secondary threads run. Instead, the main
thread should join with all the secondary threads prior to terminating. You
would typically accomplish this by designing some mechanism to notify the
secondary threads to terminate and then use WaitForSingleObject or its
Multiple variants to join with them.
 
J

Jack

1. Add the following to the top:

#include <windows.h>
#include <iostream>
using namespace std;

2. Delete the "......." line.

3. Compile with cl -EHsc -MD a.cpp.
Thanks a lot. I am learning Win32 thread. I compiled my code from the
MENU of the window, i.e., clicking the "Build" button. How should I set
up "Project Properties" to get the options of the above command line?

By the way, if I also want to run the above command line, which
directory should I enter?

Jack
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top