简体   繁体   中英

Is it safe to declare a mutex at file-scope?

I realize this question is similar, but mine is not specific to Windows.

Is is safe and good form to declare a mutex at file-scope like so?

#include <iostream>
#include <mutex>
#include "Logger.h"

mutex my_mutex;

void Logger::log()
{
    lock_guard<mutex> lock(my_mutex);
    for (int i = 0; i < 29; ++i)
    {
        cout << i << " ";
    }
    cout << endl;
}

To truly limit this to file scope in a modern C++ style:

namespace {
   mutex my_mutex;
   <information to protect goes here>
}

Then the answer is, "yes it is safe".

In your case, however, it appears that you are attempting to protect std::cout. Since cout is not limited to your file scope, your mutex is not going to do much good unless you can guarantee that this is the only use of cout and/or cerr in the entire program.

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