我想创建两个并发访问向量的线程,这样每隔10毫秒就会一直在向量的后面推送元素,另一个只是监视向量以查看它的大小是否已经改变。在这里,我得到错误“解锁无主互斥锁”,请你告诉我原因。
class SafeVec
{
public:
SafeVec(){}
~SafeVec(){}
void safePushBack(int val)
{
vecMutex.lock();
vec.push_back(val);
vecMutex.unlock();
}
size_t safeGetSize()
{
vecMutex.lock();
size_t size = vec.size();
vecMutex.unlock();
return size;
}
private:
std::vector<int> vec;
std::mutex vecMutex;
};
class safeStream
{
public:
safeStream(){}
~safeStream(){}
void Test()
{
std::thread t(&safeStream::tMonitorVec, this); // spawned a new thread
for (size_t i = 0; i < 100; i++)
{
myVec.safePushBack(1);
Sleep(10);
}
stopMonitoringMutex.lock();
stopMonitoring = true;
stopMonitoringMutex.unlock();
}
private:
void tMonitorVec()
{
stopMonitoring = false;
size_t tempSize = myVec.safeGetSize();
int count = 0;
stopMonitoringMutex.lock();
while (1)
{
if (stopMonitoring)
{
stopMonitoringMutex.unlock();
break;
}
else
{
stopMonitoringMutex.unlock();
if (tempSize != myVec.safeGetSize())
{
count++;
}
}
}
std::cout << count;
}
SafeVec myVec;
bool stopMonitoring;
std::mutex stopMonitoringMutex;
};
int main()
{
safeStream myStream;
myStream.Test();
return 0;
}
答案 0 :(得分:3)
这发生在你的循环中:
while (1)
{
if (stopMonitoring)
{
stopMonitoringMutex.unlock();
break;
}
else
{
// Whoops! I am here again !
stopMonitoringMutex.unlock();
if (tempSize != myVec.safeGetSize())
{
count++;
}
}
}
还需要考虑的另一件事是:如果您仅使用std::mutex
来保护对字段bool stopMonitoring;
的并发访问,请使用std::atomic<bool> stopMonitoring;
,而忘记互斥锁。