gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:45:52 31 4
gpt4 key购买 nike

以下程序仍然将输出交织到 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com