C + + thread creation passed parameter changed

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.