Hi SO! Is there, by any change, a possibility that the "waiting thread" does not get the "buff" updated? should i put a lock_guard in the thread that changes the "buff"? I've been reading about memory fences on some articles, like this one: http://ift.tt/2a6UBlN and i am just worried about it. Thanks in advance...
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
int main(){
std::atomic<bool> ready(false);
char buff[20]= "hello";
std::cout << "creating thread to change \"buff\"..." << std::endl;
std::thread tr(
[ & ready, & buff ](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
//should i put a lock_guard here?
buff[0]= 'w'; buff[1]= 'o';
buff[2]= 'r'; buff[3]= 'l';
buff[4]= 'd'; buff[5]= '\0';
std::cout << "buffer changed! sending signal to waiting thread..." << std::endl;
ready= true;
});
std::cout << "...waiting for the change..." << std::endl;
while(!ready);
std::cout << "...got it! buff=" << buff << std::endl;
}
Aucun commentaire:
Enregistrer un commentaire