C++ thread退出线程 多线程 子线程控制退出主线程 window VS2017 Debug Error! Abort() has been called.

  • 时间:
  • 浏览:
  • 来源:互联网

用thread创建的多线程,在子线程中,控制主程序退出,如果没有等到子线程执行并结束线程,报错:Debug Error! Abort() has been called. 如下图:

 

 

 

 

 

 

 

 

 

代码的原理:

1、子线程改变控制主线程的变量值后,使用break跳出线程的主循环while;

2、在mian里面判断到变量的值,增加线程.join(),这个函数是一直阻塞,直到子线程运行完。

 

代码:

#include <iostream>
#include <windows.h>
#include <conio.h>
#include <thread>

using namespace std;

int cycle = 1;
int cycle_control = 0;

void keyboard_hit() 
{
	char cin_char[20];
	string cin_str = " ";
	while (true)
	{
		while (!_kbhit())
		{
			Sleep(1);
		}
		cout << "检测到键盘输入,请输入完成的命令=";
		cin >> cin_char;
		cin_str = cin_char;
		if (cin_str == "exit")
		{
			cycle_control = 1;
			cout << "跳出线程的while,在.join出阻塞出等待线程运行完接着运行" << "\n";
			break;
		}
	}
}

int main() 
{
	thread t_keyboard_hit = thread(keyboard_hit);
	//t_keyboard_hit.join();

	while (cycle)
	{
		cout << "main" << endl;
		Sleep(10000);
		if (cycle_control == 1)
		{
			cout << "maian_exit" << endl;
			cout << "等待线程运行结束..." << endl;
			t_keyboard_hit.join();
			cycle = 0;
		}
	}
}

运行结果:

 

本文链接http://xiahunao.cn/article/show-994415.html