简体   繁体   中英

C++ Mutex and Function Arguments

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.

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).

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 .)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM