c++ - 线程安全的 std::cout

标签 c++ thread-safety cout

以下程序仍然将输出交织到 std::cout。我试过add a std::mutex to control access通过 std::lock_guardstd::cout,但它 still interleaves .

#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>

std::mutex global_mtx{};

class Timer {
public:
    Timer(size_t time, const std::function<void(void)>& f) : time{std::chrono::milliseconds{time}}, f{f} {}
    ~Timer() { wait_thread.join(); }

private:
    void wait_then_call()
    {
        std::unique_lock<std::mutex> lck{mtx};
        for(int i{10}; i > 0; --i) {
            {
                std::lock_guard<std::mutex>{global_mtx};
                std::cout << "Thread " << wait_thread.get_id() << " countdown at: " << '\t' << i << std::endl;

            }
            cv.wait_for(lck, time / 10);
        }
        f();
    }
    std::mutex mtx;
    std::condition_variable cv{};
    std::chrono::milliseconds time;
    std::function <void(void)> f;
    std::thread wait_thread{[this]() {wait_then_call(); }};
};

int main()
{
    auto f = []() {std::lock_guard<std::mutex>{global_mtx}; std::cout << "---------------- I waited to print! ----------------" << std::endl; };
    Timer t1{3'000,f};
    Timer t2{6'000,f};
    Timer t3{2'000,f};
    Timer t4{1'000,f};
}

我是否需要通过单独的类或专用线程来控制访问?

最佳答案

您的问题在这里:std::lock_guard<std::mutex>{global_mtx};创建一个锁守卫并立即释放它。您需要创建一个变量来持有锁,例如 std::lock_guard<std::mutex> lock{global_mtx}; .

关于c++ - 线程安全的 std::cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153079/

相关文章:

python - tkinter 的 `after` 方法线程安全吗?

c# - 访问 Dictionary<TKey, TValue> Keys 属性线程安全吗?

C++ 类和函数输出问题

c++ - 使用 Flex 和 Bison 将 Makefile 转换为 CMake

C++ 二维动态数组崩溃

c++ - 如何提高将数据推送到互斥锁定队列的性能

c++ - 使用 C++ 在终端上并排打印两个表格

c++ - 如何将 std::valarray<double> 与 gsl 集成?

c++ - boost BGL 线程安全

c++ - 循环中的 Cout 不按定义逐个打印字符