【发布时间】:2015-03-14 23:47:35
【问题描述】:
我有一个标准向量和多个线程。我正在使用以下代码在需要时锁定:
boost::mutex::scoped_lock lock(mutex);
这工作正常,应用程序运行没有任何问题,但现在我为矢量创建了一个小类以使我的生活更轻松:
template <class T> class FVector
{
private:
std::vector<T> standard_vector;
mutable boost::mutex mutex;
public:
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::size_type size_type;
FVector(void)
{
}
iterator begin(void)
{
boost::mutex::scoped_lock lock(mutex);
return standard_vector.begin();
}
iterator end(void)
{
boost::mutex::scoped_lock lock(mutex);
return standard_vector.end();
}
void push_back(T & item)
{
boost::mutex::scoped_lock lock(mutex);
standard_vector.push_back(item);
}
void erase(iterator it)
{
boost::mutex::scoped_lock lock(mutex);
standard_vector.erase(it);
}
};
但不幸的是,它不起作用。我只是得到 xx.exe 已触发断点。 异常,这意味着锁和多个线程尝试同时写入和读取存在问题。
我正在使用以下代码进行测试:
#include <Windows.h>
#include <process.h>
#include "thread_safe_vector.h"
struct TValue
{
int value;
};
FVector<TValue> vec_Safe;
boost::mutex testMutex;
void thread2(void* pArg)
{
while (true)
{
//boost::mutex::scoped_lock lock(testMutex);
for (FVector<TValue>::iterator it = vec_Safe.begin(); it != vec_Safe.end(); it++)
{
if (it->value == 5)
{
vec_Safe.erase(it);
break;
}
}
}
}
void thread1(void* pArg)
{
while (true)
{
TValue value;
value.value = 5;
//boost::mutex::scoped_lock lock(testMutex);
vec_Safe.push_back(value);
}
}
void main(void)
{
HANDLE hThreads[50];
for (size_t i = 0; i < 50; i++)
{
hThreads[i] = (HANDLE)_beginthread(i % 2 == 0 ? thread1 : thread2, NULL, NULL);
}
system("pause");
for (size_t i = 0; i < 50; i++)
{
TerminateThread(hThreads[i], 0);
}
}
我完全没有想法,我试图找出问题几个小时......我做错了什么吗?
【问题讨论】:
标签: c++ multithreading boost locking mutex