Look at the code below, what do you think the output will be?
1#include"stdafx.h"2#include <windows.h>3#include <iostream>4 using namespacestd;5 6 DWORD WINAPI Func (LPVOID p);7typedefstruct 8 {9 intFirstargu;Ten LongSecargu; One A }mytype; - - the - voidTest () - { -MyType mytypeargu={0}; +mytypeargu.firstargu=1; -mytypeargu.secargu=1; +CreateThread (NULL,0, Func,&mytypeargu,0, NULL);
Sleep (+); A } at - voidMain () - { - test (); -System"Pause"); - } in DWORD WINAPI Func (LPVOID p) - { tomytype* param= (mytype*) p; + intIntvalue=param->Firstargu; - LongLongvalue=param->Secargu; thecout <<"firstargu="<<intValue<<endl<<"secargu="<<longValue<<"."<<Endl; *cout<<"Please wait ..."<<endl<<Endl; $ return 0;Panax Notoginseng}
The final output is not really certain.
Not output
Firstargu=1
Secargu=1
The key is that after CreateThread creates the thread, after passing the pointer to the thread method, the test method exits, freeing the mytype memory, causing the thread to receive the pointer again, accessing the memory, but not the original data.
If you want to output the correct results, simply cancel the//sleep (1000) Comment, wait for the thread method to access it, and then exit.
C + + thread creation passed parameter changed