Reputation: 31
I have a c++ program on linux with two threads Thread A writes some data to a std::map No other data will ever be written to this map then Thread A creates thread B Thread B reads data from the map
So in this situation do I need to use a Mutex ?
If not then where is this guarantee specified.
Upvotes: 3
Views: 139
Reputation: 393029
In fact, the dominant pattern, whenever possible, should be:
(mutable) data moves with the tasks
So, data is owned by the thread that uses it. Now, it doesn't need to "physically" migrate, but using move semantics makes the picture a lot clearer:
#include <map>
#include <string>
using namespace std;
using Map = map<string, int>;
Map worker(Map&& data)
{
for (auto& el : data)
el.second *= -1;
return std::move(data);
}
#include <cassert>
#include <iostream>
#include <future>
int main()
{
Map global
{ { "one", 1 },
{ "two", 2 },
{ "three", 3 } };
auto background = async(worker, std::move(global));
assert(global.empty()); // data now owned by the worker thread!
global = background.get(); // await the result from the worker
for (auto const& el: global) // now the data is owned by the main thread
std::cout << el.first << ": " << el.second << "\n";
}
Note the assert
in the middle of main
: concurrent access isn't even possible.
See it Live on Coliru.
Upvotes: 1
Reputation: 477040
No. Thread creation is a synchronization point, so all the effects that the first thread produced before creating the second thread will "have happened" by the time the second thread is created (in a way that can be made precise in the language of the standard).
To be slightly more precise, in the context of one thread creating and later joining another thread...
Upvotes: 5
Reputation: 390
No, mutex is only needed when you want to read/write to the memory from two or more threads simultaniously. Since, when you have more than one thread, your std::map is immutable, you do not need any syncronization. You dont ever need mutexes on immutable data. And even if in your case thread B would write to the std::map, still only one thread would r/w on this memory at once and you dont need to syncronize one thread.
Upvotes: 2