Reputation: 18168
I know that I can use semaphore or mutex and ..., but I like to know if there is any problem if I write to a variable in one thread and read it in another thread? something such as this:
#include <iostream>
#include <thread>
volatile int value=0;
int main()
{
auto workerThread = new std::thread([&]()
{
for(int i=0;i<10000;++i)
{
value=i;
std::this_thread::sleep_for(std::chrono::milliseconds(i*100));
}
}
);
while(true)
{
std::cout<<value<<std::endl;
if(value >1000) break;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
Is it a safe application and there is no smell in it?
Without any complexity, can I improve it?
Upvotes: 0
Views: 75
Reputation: 385144
No, it's not "safe".
Whoever told you that volatile
was what you needed to make this safe was wrong.
Either wrap access to value
in a mutex or semaphore, or make it an std::atomic<int>
.
Also note that:
std::cout<<value<<std::endl;
if(value >1000) break;
may each read different value. You may want to read it only once:
int v = value;
std::cout << v << std::endl;
if(v > 1000) break;
Upvotes: 7