Multithreading 你应该如何使用C++;14具有lambda捕获和多线程的共享互斥锁?
我有一些非常简单的代码,应该通过同时启动10个线程来测试多线程记录器,这些线程将同时写入记录器 我希望看到所有10条消息,而不是以任何顺序;然而,我随机得到5、6、7、8、9条,有时还有10条输出消息 代码如下:Multithreading 你应该如何使用C++;14具有lambda捕获和多线程的共享互斥锁?,multithreading,lambda,c++14,mutex,Multithreading,Lambda,C++14,Mutex,我有一些非常简单的代码,应该通过同时启动10个线程来测试多线程记录器,这些线程将同时写入记录器 我希望看到所有10条消息,而不是以任何顺序;然而,我随机得到5、6、7、8、9条,有时还有10条输出消息 代码如下: //*.cxx #include <iostream> #include <mutex> #include <shared_mutex> // requires c++14 #include <string> #include <t
//*.cxx
#include <iostream>
#include <mutex>
#include <shared_mutex> // requires c++14
#include <string>
#include <thread>
#include <vector>
namespace {
std::mutex g_msgLock;
std::shared_timed_mutex g_testingLock;
}
void info(const char * msg) {
std::unique_lock<std::mutex> lock(g_msgLock);
std::cout << msg << '\n'; // don't flush
}
int main(int argc, char** argv) {
info("Start message..");
std::vector<std::thread> threads;
unsigned int threadCount = 10;
threads.reserve(threadCount);
{ // Scope for locking all threads
std::lock_guard<std::shared_timed_mutex> lockAllThreads(g_testingLock); // RAII (scoped) lock
for (unsigned int i = 0; i < threadCount; i++) {
// Here we start the threads using lambdas
threads.push_back(std::thread([&, i](){
// Here we block and wait on lockAllThreads
std::shared_lock<std::shared_timed_mutex> threadLock(g_testingLock);
std::string msg = std::string("THREADED_TEST_INFO_MESSAGE: ") + std::to_string(i);
info(msg.c_str());
}));
}
} // End of scope, lock is released, all threads continue now
for(auto& thread : threads){
thread.join();
}
}
请注意,此运行只有8个输出。有趣的是,此问题与我的生成系统有关,该系统正在删除消息。可执行文件总是按照预期生成输出。无论如何,无法复制。我总是看到打印的10条消息。@IgorTandetnik谢谢您的尝试!你用了什么编译器?这个链接应该复制:其中三个:,我使用过MSVC和GCC,我看到了相同的行为,因为这似乎是一种竞争条件,我想知道你的硬件是否因为某种原因没有显示出故障。当我使用MSVC时,我会收到2-5条消息,但使用GCC我会收到5-10条消息。在这里看不到任何数据。
Start message..
THREADED_TEST_INFO_MESSAGE: 9
THREADED_TEST_INFO_MESSAGE: 5
THREADED_TEST_INFO_MESSAGE: 3
THREADED_TEST_INFO_MESSAGE: 1
THREADED_TEST_INFO_MESSAGE: 4
THREADED_TEST_INFO_MESSAGE: 0
THREADED_TEST_INFO_MESSAGE: 8
THREADED_TEST_INFO_MESSAGE: 7