I am writing some C ++ 11 code with threads, and I'm not quite sure when I need to use a memory fence or something like that. So, here is basically what I am doing:
class Worker
{
std::string arg1;
int arg2;
int arg3;
std::thread thread;
public:
Worker( std::string arg1, int arg2, int arg3 )
{
this->arg1 = arg1;
this->arg2 = arg2;
this->arg3 = arg3;
}
void DoWork()
{
this->thread = std::thread( &Worker::Work, this );
}
private:
Work()
{
}
}
int main()
{
Worker worker( "some data", 1, 2 );
worker.DoWork();
return 0;
}
I was wondering what steps I need to take to make sure that the arguments are safe to access in the Work () function, which works in another thread. Is it enough that it is written in the constructor, and then the stream is created in a separate function? Or do I need a memory fence, and how to make a memory fence to make sure that all 3 arguments are written by the main stream and then read by the Worker stream?
Thanks for any help!
source
share