My application keeps a global shared pointer and multiple threads are taking copies from that shared pointer while it is being changed by another thread?
Is this safe? Else what is the correct way of doing this?
Code:
#include <iostream>
#include <memory>
#include <thread>
class Configuration
{
public:
Configuration(uint64_t value) { m_value = value; }
virtual ~Configuration() {}
uint64_t getValue() const { return m_value; }
private:
uint64_t m_value;
};
std::shared_ptr<Configuration> g_configuration = nullptr;
void outputProcessing()
{
uint64_t sum = 0;
while (true)
{
auto configuration = g_configuration;
sum += configuration->getValue();
}
}
void inputProcessing()
{
uint64_t value = 1;
while (true)
{
auto configuration = std::make_shared<Configuration>(value++);
g_configuration = configuration;
}
}
int main(const int argc, const char** argv)
{
g_configuration = std::make_shared<Configuration>(0);
std::thread inputThread(inputProcessing);
std::thread outputThread1(outputProcessing);
std::thread outputThread2(outputProcessing);
std::thread outputThread3(outputProcessing);
inputThread.join();
outputThread1.join();
outputThread2.join();
outputThread3.join();
return EXIT_SUCCESS;
}
In this application one thread creates new shared pointers and assign to the global pointer which other threads are copying the same.
If this is not thread safe, what is the option?
Please forget about the actual functionalities implemented in the output thread.