您应该如何将C ++ 14共享互斥体与lambda捕获和多个线程一起使用?

时间:2018-08-17 13:31:45

标签: 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 <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();
    }
}

输出通常是以下形式:

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

请注意,此运行只有8个输出。

1 个答案:

答案 0 :(得分:0)

有趣的是,这个问题与我的构建系统有关,该系统正在丢弃消息。可执行文件始终会按预期产生输出。