Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 此线程::影响其他线程的睡眠线程_C++_Multithreading_C++11_Future - Fatal编程技术网

C++ 此线程::影响其他线程的睡眠线程

C++ 此线程::影响其他线程的睡眠线程,c++,multithreading,c++11,future,C++,Multithreading,C++11,Future,我有一个带有两个线程的简单程序,一个线程将打包的_任务推入deque,另一个线程执行它。在任务中有一个this_thread::sleep_for,我希望只有“process”线程会等待它,但两者都在等待,使执行顺序有序。我错过了什么 #include <future> #include <iostream> #include <deque> std::mutex m; std::condition_variable cv; std::deque<st

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

#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::互斥m;
std::条件变量cv;
std::德克-德克;
空缺职位(){
int id=0;
自动lambda=[](int-id){
std::this_thread::sleep_for(std::chrono::seconds(std::rand()%10+1));

std::cout我认为更有效的方法是使用睡眠随机秒…

我认为更有效的方法是使用睡眠随机秒…

打包的任务本身不是异步的。它可以传递给线程构造函数,因为它是可调用的,但没有为您自动创建后台线程可能您想使用
std::launch::async
?为什么要调用
任务(id++)创建
任务后立即在
post
?是否打算绑定
id
的值,以便在最终调用lambda时将其作为参数传递?@Someprogrammerdude很好。我会试试。@G.M.你的意思是像
任务一样创建(std::bind(lambda,id++)
?我认为两种方法都是等效的……我想我必须更仔细地阅读文档。ThanksA
打包的任务本身不是异步的。它可以传递给线程构造函数,因为它是可调用的,但没有自动为您创建后台线程。也许您需要使用
std::launch::async
?为什么在创建
任务后立即调用
任务(id++);
中的
发布
任务后立即调用
?目的不是要绑定
id
的值,以便在最终调用lambda时将其作为参数传递吗?@Someprogrammerdude很好。我会尝试一下。@G.M.你的意思是创建类似
任务吗(std::bind(lambda,id++)
?我想这两种方法都是等效的……我想我必须更仔细地阅读文档。谢谢