Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Should data passed to a thread be volatile?

In Microsoft Visual C++ I can call CreateThread() to create a thread by starting a function with one void * parameter. I pass a pointer to a struct as that parameter, and I see a lot of other people do that as well.

My question is if I am passing a pointer to my struct how do I know if the structure members have been actually written to memory before CreateThread() was called? Is there any guarantee they won't be just cached? For example:

struct bigapple { string color; int count; } apple;
apple.count = 1;
apple.color = "red";
hThread = CreateThread( NULL, 0, myfunction, &apple, 0, NULL );

DWORD WINAPI myfunction( void *param )
{
    struct bigapple *myapple = (struct bigapple *)param;

    // how do I know that apple's struct was actually written to memory before CreateThread?
    cout << "Apple count: " << myapple->count << endl; 
}

This afternoon while I was reading I saw a lot of Windows code on this website and others that passes in data that is not volatile to a thread, and there doesn't seem to be any memory barrier or anything else. I know C++ or at least older revisions are not "thread aware" so I'm wondering if maybe there's some other reason. My guess would be the compiler sees that I've passed a pointer &apple in a call to CreateThread() so it knows to write out members of apple before the call.

Thanks

like image 203
loop Avatar asked Sep 11 '12 05:09

loop


1 Answers

No. The relevant Win32 thread functions all take care of the necessary memory barriers. All writes prior to CreateThread are visible to the new thread. Obviously the reads in that newly created thread cannot be reordered before the call to CreateThread.

volatile would not add any extra useful constraints on the compiler, and merely slow down the code. In practice thiw wouldn't be noticeable compared to the cost of creating a new thread, though.

like image 106
MSalters Avatar answered Sep 24 '22 04:09

MSalters