我想在c++的mmorpg中使用多线程,我现在有5个线程,我想把另一个一分为二,但是我的mmorpg服务器包含了大量的向量,而且因为向量不是线程安全的,所以我不能正确地写。
是否有替代跨线程使用向量的方法,或者是否有方法使向量读/写多线程安全。
这里有一个我不想要的例子,试着找到一个类似这样的东西的替代品:很明显,这不是实际的代码,我只是做一个例子。
//Thread1
//Load monster and send data to the player
globals::monstername[myid];//Myid = 1 for now -.-
senddata(globals::monstername[myid]);//Not the actual networking code, im just lazy.
//Thread2
//Create a monster and manage it
globals::monstername.push_back("FatBlobMonster");
//More managing code i cant be bothered inserting >.<发布于 2012-07-26 21:32:58
两件事。
发布于 2012-07-26 21:30:38
我不知道有任何线程安全的向量类。但是,您可以自己创建一个使用std::vector和一个std::mutex (在C++11中):
template <typename T>
class LockedVector {
private:
std::mutex m;
std::vector<T> vec;
};使用std::lock锁定互斥锁。
https://stackoverflow.com/questions/11670314
复制相似问题