Click here to Skip to main content
15,905,612 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my VC++ code

CWinThread* Serial_Thread[3];

_tmain(int argc, char* argv[])
{

for(int i = 0 ; i < 3; i++)
{
Serial_Thread[i] = AfxBeginThread(SendSerial_Thread, &i);
}
}
and
static UINT SendSerial_Thread(LPVOID pParam)
{
int x = (int)pParam;
}

But when debugging,
the last x of thread is not equal of i of main program;
(if i=0, x=4060628....)

I thought it is simple.
But now, I don't know why or where is my fault....
Please let me know

Thank in advance.

What I have tried:

2 more hours wasted for this problem...
Posted
Updated 17-Jun-17 5:03am

1 solution

pParam is a pointer to int not an int. Should be
C++
static UINT SendSerial_Thread(LPVOID pParam)
{
    int x = *reinterpret_cast<PINT>(pParam);
}
 
Share this answer
 
Comments
Member 12330615 18-Jun-17 22:13pm    
After modifying according of your advice, and careful testing, I found testing almost applied. But sometimes x had same error....
Richard MacCutchan 19-Jun-17 4:41am    
The variable x only exists within the for loop. So once that loop ends there is no guarantee that is will hold the expected value. In fact, once that loop ends the main thread may also end as it does not wait for any of the child threads to complete. You should use a variable (and a main thread) that will exist for the lifetime of all threads that may refer to it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900