C++并发与多线程(4) | 传递临时对象作为线程参数的一些问题Ⅰ

 

一、陷阱1

  写一个传递临时对象作为线程参数的示例:

#include 
#include 
#include 
using namespace std;

void myprint(const int& i, char* pmybuf)
{
	cout << i << endl;
	cout << pmybuf << endl;
	return;
}

int main()
{
	int mvar = 1;
	int& myarray = mvar;
	char mybuf[] = "this is a test!";
	thread mytobj(myprint, mvar, mybuf); // 括号后面两个参数就是线程函数的两个输入参数
	mytobj.join();

	cout << "main over" << endl;
	return 0;
}

    运行结果:

C++并发与多线程(4) | 传递临时对象作为线程参数的一些问题Ⅰ_第1张图片

  如果将join()改为detach()。运行时加上断点,然后监视几个变量的地址:

C++并发与多线程(4) | 传递临时对象作为线程参数的一些问题Ⅰ_第2张图片

你可能感兴趣的:(C++,c++)