Bir*_*ibu 3 c++ multithreading mutex c++11
我正在努力让这项工作正常进行,但似乎有一些我不完全理解的事情。
\n\n我在一个文件中有一个多线程应用程序(2个类和我在其中创建线程和所有内容的真正的主程序)。我想分成3个文件。一个用于每个类(及其标题),一个用于主类。
\n\n我有几个 mutices 和一个队列来在线程之间共享消息并随时锁定和解锁它们。
\n\n我想编写一个单例类,以便所有类都可以共享互斥锁:
\n\n标头:
\n\n#ifndef COMMONSINGLETON_H\n#define COMMONSINGLETON_H\n\n#include <mutex> // std::mutex\n#include <queue>\n\nclass CommonSingleton{\n private:\n static std::mutex mutex_w_b;\n //static std::mutex mutex_wifi_ok;\n //static std::queue <std::string> queue_w_b;\n\n public:\n static CommonSingleton& getInstance();\n std::mutex GetMutexWB();\n //std::mutex GetMutexWiFiOk();\n //std::queue <std::string> GetQueueWB();\n private:\n CommonSingleton() {};\n CommonSingleton(CommonSingleton const&);\n void operator=(CommonSingleton const&);\n};\n#endif\nRun Code Online (Sandbox Code Playgroud)\n\n我的 .cpp 文件:
\n\n#include "commonsingleton.h"\n\nstatic CommonSingleton& CommonSingleton::getInstance(){\n static CommonSingleton instance;\n return instance;\n}\nstd::mutex CommonSingleton::GetMutexWB(){\n return mutex_w_b;\n}\n/*std::mutex CommonSingleton::GetMutexWiFiOk(){\n return mutex_wifi_ok;\n}\nstd::queue <std::string> CommonSingleton::GetQueueWB(){\n return queue_w_b;\n}*/\nRun Code Online (Sandbox Code Playgroud)\n\n在我的主要内容中,我有这个来测试互斥体:
\n\nCommonSingleton::getInstance().GetMutexWB.lock();\nRun Code Online (Sandbox Code Playgroud)\n\n但现在我评论了,只是为了弄清楚如何编译。这是我得到的错误:
\n\ncommonsingleton.cpp:4:54: error: cannot declare member function \xe2\x80\x98static \nCommonSingleton& CommonSingleton::getInstance()\xe2\x80\x99 to have static linkage [-\nfpermissive]\nstatic CommonSingleton& CommonSingleton::getInstance(){\n ^\ncommonsingleton.cpp: In member function \xe2\x80\x98std::mutex \nCommonSingleton::GetMutexWB()\xe2\x80\x99:\ncommonsingleton.cpp:9:12: error: use of deleted function \n\xe2\x80\x98std::mutex::mutex(const std::mutex&)\xe2\x80\x99\nreturn mutex_w_b;\n ^\nIn file included from commonsingleton.h:5:0,\nfrom commonsingleton.cpp:1:\n/usr/include/c++/4.8/mutex:128:5: error: declared here\nmutex(const mutex&) = delete;\nRun Code Online (Sandbox Code Playgroud)\n\n我在这里做错了什么?
\n你不需要那么多样板。你只需要一个函数:
std::mutex& getCommonMutex() {
static std::mutex m;
return m;
}
Run Code Online (Sandbox Code Playgroud)
就这样,您可以从任何地方调用此函数,并且它将始终返回对同一互斥体的引用,该互斥体将在第一次调用时进行初始化。