关于子线程释放的时机

阅读更多
void test() {
	ThreadRunner mThread("test");
	int mCount = 1;
	mThread.start([&mCount] {
		mCount++;
		printf("thread run...%d\n", mCount);
		std::chrono::milliseconds sleepDuration(2000);
		std::this_thread::sleep_for(sleepDuration);
		return true;
	});
	cout << "test end..\n" << endl;
}

int main()
{
	test();
	cout << "test out..\n" << endl;
}
ThreadRunner created. name:test
ThreadRunner created. name:test
test end..
ThreadRunner started. name:test
thread run...2

thread run...3
thread run...4
thread run...5
thread run...6
thread run...7
thread run...8
thread run...9
thread run...10
thread run...11
thread run...12
thread run...13
thread run...14
thread run...15
thread run...16

     由于test()函数退出时会对ThreadRunner进行析构,而子线程循环运行,永远无法析构,导致main()函数无法执行到下一步。也就是说,虽然启动了子线程,但main()要等待子线程执行完毕。函数局部变量子线程会引起函数阻塞无法退出。

static ThreadRunner mThread("test");

void test() {
	int mCount = 1;
	mThread.start([&mCount] {
		mCount++;
		printf("thread run...%d\n", mCount);
		std::chrono::milliseconds sleepDuration(2000);
		std::this_thread::sleep_for(sleepDuration);
		return true;
	});
	cout << "test end..\n" << endl;
}

int main()
{
	test();
	cout << "test out..\n" << endl;
}
ThreadRunner created. name:test
test end..
ThreadRunner started. name:test

thread run...2
test out..

请按任意键继续. . . thread run...1946155304
thread run...1946155305
thread run...1946155306
thread run...1946155307
thread run...1946155308
thread run...1946155309
thread run...1946155310
thread run...1946155311
thread run...1946155312

    由于ThreadRunner是全局的,函数test() 退出时并不会引起ThreadRunner析构,所以也不会阻塞main()运行。但是mCount局部变量已经释放,所以子线程中的mCount引用的值是随机数。不要传递局部变量的引用给子线程。

 

static ThreadRunner *mThread = nullptr;

void test(const int mCount) {
	if (mThread == nullptr) {
		mThread = new ThreadRunner("test");
	}
	if (mThread->isRunning()) {
		delete mThread; // 会阻塞等待前一个线程析构,如果不delete,则前一个线程成为野指针
		mThread = new ThreadRunner("test2");
	}
	mThread->start([mCount] {
		printf("thread run...%d\n", mCount);
		std::chrono::milliseconds sleepDuration(2000);
		std::this_thread::sleep_for(sleepDuration);
		printf("thread run.end..%d\n", mCount);
		return false;
	});
	cout << "test end..\n" << endl;
}

int main()
{
	test(1);
	cout << "test out..\n" << endl;
	test(2);
	cout << "test out.2.\n" << endl;
}

 

你可能感兴趣的:(关于子线程释放的时机)