Question Motivation
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.
Example Code
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.
` tags, please use the Markdown code formatting facilities. See here: http://stackoverflow.com/editing-help#code. I took the liberty of editing it your post this time.
– R. Martinho Fernandes Jul 09 '13 at 14:13