Reputation: 4912
I'm new to std::atomic
. If I understand it correctly, such variables can't be accessed by more than one thread at a time, and threads are forced to take turns if they try to do so.
I have an std::vector<std::string>
that I need to make atomic. What's the simplest, most fool-proof way to do this?
I have 2 threads. One occasionally pushes strings into the vector, and the other thread continuously reads then erases all strings from the vector.
// about one per second
// this function is exported from DLL 2
myVector.push_back(myString);
while (true) {
if (myVector.size() > 0) {
std::string myString = myVector.at(0);
std::string myCopy;
myCopy.assign(myString);
myVector.erase(myVector.begin());
}
}
Upvotes: 1
Views: 785
Reputation: 13679
The goal of having "simplest, most fool-prof thing" and the goal to handle a complex data structure as atomic
contradict each other.
One way of pursuing your goal is to have lock-based approach. The comments are suggesting that. Generally, lock-based approach has its own caveats (with deadlocks and starvations), but for your case it will work, though may be still sub-optimal.
What you need seems like a produce-consumer queue. Single producer, single consumer.
If you have the expectation of high performance, it should be lock-free, ring-buffer based.
boost::lockfree::spsc_queue
is one possible implementation. There are other implementations.
Also you may want to avoid string allocation and have boost::lockfree::spsc_queue<char>
, and delimit strings by \0
.
If you want even faster that that, you may have own implementation, optimized for your scenario.
But if you say "One occasionally pushes strings into the vector", and occationally means infrequently, you may want lock-based queue instead.
Boost.Thread has Synchronized Queues -- EXPERIMENTAL. There are other implementations.
The advantage of that instead of using mutex
/ condition_variable
directly is that you don't have to write your own synchronization, so it really meets "simplest, most fool-prof thing"
I actually implement hybrid approach in my program. Which turns to lock-based when it needs to wait, but otherwise is lock-free. I haven't seen a good open-source implementations of such, but I would like to see.
Upvotes: 2