繁体   English   中英

this_thread :: sleep_for影响其他线程

[英]this_thread::sleep_for affecting other thread

我有一个带有两个线程的简单程序,一个将packaged_task推送到deque ,另一个执行它。 在任务中有一个this_thread::sleep_for ,我希望只有“进程”线程会等待它,但两者都在等待,使执行顺序。 我错过了什么?

#include <future>
#include <iostream>
#include <deque>

std::mutex m;
std::condition_variable cv;
std::deque<std::packaged_task<void(int)>> deque;

void post() {
    int id = 0;
    auto lambda = [](int id) {
        std::this_thread::sleep_for(std::chrono::seconds(std::rand() % 10 + 1)); 
        std::cout << id << std::endl;
    };
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        std::packaged_task<void(int)> task(lambda);
        task(id++);

        std::lock_guard<std::mutex> lg(m);
        deque.emplace_back(std::move(task));

        cv.notify_one();
    }
}

void process() {
    std::deque<std::packaged_task<void(int)>> to_exec;
    while (true) {

        while (!to_exec.empty()){
            std::future<void> fut = to_exec.front().get_future();
            fut.get();

            to_exec.pop_front();
        }

        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []() {return !deque.empty(); });

        while (!deque.empty()) {
            to_exec.push_back(std::move(deque.front()));
            deque.pop_front();
        }
    }
}

int main() {

    std::thread tpost(post);
    std::thread tprocess(process);

    tpost.join();
    tprocess.join();
}

我认为更有效的是使用std :: async而不是睡眠随机秒......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM