I want to create a thread using CreateThread API in Visual C++, below is my
code, but when I try to execute this testing program, error occurs in 7,
said that "Thread exit with code 0 ...". What's wrong?
Thanks in advance
Kevin
==>>
DWORD WINAPI MyThread(LPVOID lpParameter)
{
FILE *stream;
long i = 0;
while (i<5)
{
stream = fopen("c:\\temp\\Thread.txt", "a"); //Error in this line!
fprintf(stream, "%s, i = %d\n", "Kevin's best+++", i);
fclose(stream);
i++;
::Sleep(1000);
}
return 0;
}
void TestThread()
{
::CreateThread(NULL, NULL, &MyThread, NULL, NULL, NULL);
// MyThread(NULL);
}
The message 'Thread exited with code 0...' is simply an informational
message indicating that a thread finished its line of execution. The code of
'0' normally means it finished without an error.
One thing that could be causing you a problem is your main thread (the one
calling TestThread()), exiting before your second thread having chance to do
its thing. If this is the case, look at using ::WaitForSingleObject() on the
handle returned from ::CreateThread() - waiting on this handle from your
main thread will stop it exiting until the second thread exits.
Andy
"Kevin Dai" <kvd...@sohu.com> wrote in message
news:esebAq6BCHA.1300@tkmsftngp04...
>Hello all:
>
>I want to create a thread using CreateThread API in Visual C++, below is my
>code, but when I try to execute this testing program, error occurs in 7,
>said that "Thread exit with code 0 ...". What's wrong?
You are using fopen/fprintf/fclose, which are functions from the standard C
library, not from the WIndows API. To allow the C library to be initialised
for the thread, you should use _beginthread() or _beginthreadex() instead of
CreateThread(). This is ducmented in the C library reference in VC++
Don't forget to compile and link your application with the correct options to
ensure the multithreaded version of the C library is linked with your code.
AndyM
>==>>
>DWORD WINAPI MyThread(LPVOID lpParameter)
>{
> FILE *stream;
> long i = 0;
>
> while (i<5)
> {
> stream = fopen("c:\\temp\\Thread.txt", "a"); //Error in this line!
> fprintf(stream, "%s, i = %d\n", "Kevin's best+++", i);
> fclose(stream);
> i++;
> ::Sleep(1000);
> }
> return 0;
>}
>
>void TestThread()
>{
> ::CreateThread(NULL, NULL, &MyThread, NULL, NULL, NULL);
>}
--
GlobespanVirata, Unit 230 Science Park, Milton Road, Cambridge CB4 0WB, UK
http://www.globespanvirata.com/ Tel: +44 1223 707400 Fax: +44 1223 707447
James
--
www.catch22.uk.net
Free win32 software, sourcecode, and tutorials
------
Please remove "NOSPAM" when replying.
"Kevin Dai" <kvd...@sohu.com> wrote in message
news:esebAq6BCHA.1300@tkmsftngp04...
I now know the reason is that I am using Win32 Console Project, the main
thread will exit immediately, even before the second thread(s). I change it
to a Dialog Project, and it works fine.
Now I am going to see what ::WaitForSingleObject() will help for this case.
Thanks again
Kevin