WHCSRL 技术网

c++11 mutex destroy while busy

学习c++ 的异常捕捉模块,写了个测试例子,本来打算让线程t2整除0挂掉,然后顺便测试下死锁,结果出现了mutex destroy while busy

#include <iostream>
#include "noticer.h"
#include "observer.h"
#include "xx.h"

#include "single.h"
#include <mutex>
#include <thread>
#include <windows.h>


using namespace std;

int share = 1;
void t1()
{

	for (int i = 0; i < 1000; i++)
	{
		mutex m;
		m.lock();
		share++;
		printf("t1:%%d
", share);
		m.unlock();
	}

}
void t2()
{
	for (int i = 0; i < 100; i++)
	{
		try
		{

			mutex m;
			m.lock();
			printf("33333333333333333333333
");
			//Sleep(5000);
			throw 1;
			
			share = 99999;
			printf("t2:%%d
", share);
			m.unlock();		
		}
		catch (...)
		{
			printf("catcatfatdafdgasgstat
");
		}

	}
	printf("222222222222222222222222222222222222222
");

}


void test()
{
	int y = 0;
	int a[100];
	try {
		a[1010] = 3;
	}
	catch (...)
	{
		cout << "teststet" << endl;
	}
}
int main()
{

	//thread x(t1);
	//printf("1111111111111111111
");

	//thread y(t2);
	//mutex m;
	//m.lock();
	//share=-1000;
	//m.unlock();
	//printf("main:%%d
", share);
	//x.join();
	//y.join();
	int y = 0;
	int a[100];
	try {
		cout << "error" << endl;
		test();
		//throw 1;
		//int x = 5 / y;
		a[1001] = 10;
	}
	catch(...)
	{
		cout << "catch" << endl;
	}


	//single::getinstance()->pri();
	//

	//single::getinstance()->pri();
	//

	xx *p = new xx;


	//cout << "main start" << endl;
	//noticer ticket;
	//observer buyer1;
	//observer2 buyer2;




	//ticket.attach(&buyer1);
	//ticket.attach(&buyer2);
	//ticket.attach(&buyer2);
	//ticket.attach(&buyer2);
	//ticket.attach(&buyer2);

	//for (int i = 1; i < 100; i++)
	//{
	//	ticket.doprocess(i);
	//}



}



}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131

和python不同的是,c++并不是出现了错误就能被调用者(这里是main)捕捉,或者更深入的解释是,整除0的时候,并不能主动的抛出错误。

标准做法是,首先判断除数是否为零,如果不是则继续运算。如果除数是0,且是合法输入,那么必定有约定好的输出,或约定好没有输出。如果是非法输入,则输出错误信息,或抛出异常,或其他约定好的错误处理方式。不应过度依赖异常处理。——c++本身并不会抛出除零异常,所以必须手动检查之后手动抛出异常(如果需要的话)。如果要抛出异常,可以抛出invalid_argument,或者自定义异常。

推荐阅读