Reputation: 16585
I am using mutexes to protect some variables in a function which is the entry point of a set of threads. I think the mutex will protect the variables which are in the same scope, but will it protect the function arguments? Especially if the arguments are pointers.
Edit: Mutex is declared in main, otherwise it doesn't work - silly me.
I have a function like this:
void threadfunction(int index, char* const flag)
{
//std::mutex m;
std::lock_guard<std::mutex> lock(m);
// Is this thread safe?
if(*flag) { *flag = 0; index ++; }
}
int main()
{
std::mutex m;
std::vector<std::thread> threadvec;
threadvec.push_back(std::thread(threadfunction)); // Or whatever it is
... join ...
}
I guess you can see the problem: Since the arguments are in the same scope of the mutex, I would assume index is protected. However, although I would assume the address stored in 'char* const flag' is thread-safe, I am guessing that '*flag' is not. is this correct, and is there a solution?
Thanks
PS: Sorry to anyone who edits the question and has to deal with my horrendous attempt at html.
Upvotes: 0
Views: 1378
Reputation: 16585
For the actual code I was working on, I declared the mutex 'std::mutex mMutex' in the code with the variables which needed protection.
Then whenever a read/write to any of these variables was required, the mutex was locked then unlocked afterwards.
Probably not exception safe, but it seems to be working.
Upvotes: 0
Reputation: 153909
A mutex does not protect variables, it protects sections of
code. If all sections of code which access the data are
protected by the mutex, the data is protected. If there is any
section of code which accesses the code without holding the
mutex, then you have a race condition, and undefined behavior.
(In other words, you need to use the same mutex when you set
*flag
.)
Upvotes: 1
Reputation: 39807
Index is not "protected" but it's a local variable so there's nothing to protect. You are correct in being concerned about the contents of flag however. Your mutex prevents other threads from running the main body of this function but it does not prevent other code from accessing the memory of flag (assuming they have its address).
Upvotes: 1