I want to use multithreading in my mmorpg in c++, ive got 5 threads at the moment, and i want to split another one in two, but my mmorpg server conists of loads of vectors, and because the vectors arn't threadsafe to write, i can't do it properly.
Is there an alternative to using vectors across threads, or is there a way to make the vector read/write multithread safe.
Heres an example of what i wan't, try to find an alternative to something like this: Obviously this isn't actual code, im just making an example.
//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 >.<
Two things.
Don't store shared data in one big data structure that gets locked completely. Lock just parts of it. For example, if you must use vectors, then create a set of locks for regions of the vector. Say I have 1000 entries, I might create 10 locks, that each lock 100 consecutive entries. But you can probably do better. For example, store your monsters in a hash table, where each "bucket" in your hash table has its own lock.
Use a "read/write" lock. It is possible to create a type of lock that allows multiple readers and a single writer. So each hash bucket might have a read write lock. If no monsters are being created in a particular bucket, then multiple threads can be reading monsters out of that bucket. If you need to hash a new monster into the bucket then you lock the bucket for writing. This lock will wait for all current readers to release, and not allow more readers to lock until the write is complete. Once there are no more readers, the w rite operation succeeeds
I am not aware of any thread safe vector class. However, you could create one yourself that uses std::vector
and a std::mutex
(in C++11):
template <typename T>
class LockedVector {
private:
std::mutex m;
std::vector<T> vec;
};
You lock the mutex with std::lock
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With