今天想到一个问题:如果用类成员函数作为线程函数,那么当线程还在执行的过程中,这个类对象析构了会怎么样。动手写个小程序试试,毕竟实践是检验真理的唯一标准么。

#include <iostream>
#include <thread>
class ThreadTest
{
public:
	int i;
	void Process()
	{
		i = 0;
		while (true)
		{
			std::cout << i++ << std::endl;
			Sleep(1000);
		}
		
	}
};
int main()
{
	ThreadTest* test = new ThreadTest();
	std::thread thr(&ThreadTest::Process, test);
	Sleep(5000);
	test->i = 100;
	Sleep(5000);
	delete test;
	getchar();
} 

运行结果如下:-572662304这个会一直打印,除非主程序退出。

 用类的成员函数作为线程函数

 

就是这么回事,两个线程公用一个对象,所以在使用类对象时要时刻注意数据安全。

相关文章:

  • 2022-12-23
  • 2021-07-30
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-03-09
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案