我正在使用std :: vector作为多线程应用程序中的共享数据。我封装螺纹的类中,例如,std ::向量,线程安全,多线程
class ABC {
public:
double a, b, c;
};
boost::mutex mutex1;
class XYZ {
public:
XYZ(vector<ABC> & pVector) {
ptrVector = &pVector;
m_thread = boost::thread(&XYZ::Start, this);
}
~XYZ() {}
void Start();
public:
vector<ABC> * ptrVector;
boost::thread m_thread;
};
void XYZ::Start() {
try {
while(1) {
boost::this_thread::interruption_point();
for (unsigned int i=0; i<ptrVector->size(); i++) {
{
boost::mutex::scoped_lock lock(mutex1);
ptrVector->at(i).a = double(rand())/10000;
ptrVector->at(i).b = double(rand())/10000;
ptrVector->at(i).c = double(rand())/10000;
}
}
}
}
catch(boost::thread_interrupted) {}
catch(std::exception) {}
}
当我关闭应用程序,有时,在调试,会有2个错误消息,有时会有任何错误消息。我经常听到人们在谈论std :: vector不是线程安全的,这是这种情况之一吗?我正在使用Visual Studio 2008,boost线程,矢量的大小是固定的。任何人都可以提供一些关于如何在多线程应用程序中使用std :: vector的建议。在ETP.exe 0x7688b9bc
- 第一次机会异常:微软C++ 例外:的std :: out_of_range内存位置0x02d8f7bc ..在ETP.exe 0x00e916e0
- 第一次机会异常:0000005:访问 违规阅读地点0x00000008。
- 第二次机会断言失败:文件C:\ Program Files文件 (x86)的\微软的Visual Studio 9.0 \ VC \包括\载体,线路二 机会断言失败:文件C:\ Program Files文件(x86)的\微软 视觉studio 9.0 \ vc \ include \ vector98
谢谢。
矢量不是线程安全的,如果你尝试从不同的线程同时那么它将打破写入。尽管你正在锁定它,并且没有其他代码来查看你是如何使用它的,但是不可能知道可能发生了什么问题。这个特殊的代码本身看起来很好。 – Jarryd 2012-02-16 04:06:13
除了线程安全之外,您可能还需要考虑线程访问向量的顺序,如果一个线程正在读取向量,那么您应该确保另一个线程已经写入向量或至少您的代码应该处理矢量尚未写入的条件。 – 2012-02-16 04:13:53
@Jarryd你是仪式,在这段代码中,似乎他使用互斥锁来锁定向量,如果他这样做,那么它不应该引起问题,因为我们需要去完成代码的细节 – 2012-02-16 04:14:44