如何在C ++中使总是需要新的Input内部循环的单独进程?

我需要在while循环内运行一个函数,作为一个单独的过程,该过程将始终在每个循环中获取新的输入。我不确定该定义的正式用语是什么。我正在考虑std::thread,但不确定是否是使用线程的正确方法。示例:

void Foo(int i){
    //.....  bunches of operations
}

int main(){
    int i = 0;
    std::thread th1;
    while(i < 5)  // exit flag example
    {
        i++; //incremented i
        th1 = std::thread(Foo,i);  //run the function as separated process that takes new value of i
        // .... other operations
    }
    th1.join();  //finish processing the thread
    return 0;
}

以上程序不适用于Aborted (core dumped),我想我的C驱动器内存大大减少了,导致内存泄漏。

更新:如果我将join放入循环中,程序将正常工作

while(i < 5)
    {
        i++; //incremented i
        th1 = std::thread(Foo,i);  //run the function as separated process that takes new value of i
        std::cout<<"test"<<std::endl;
        th1.join();  //finish processing the thread
    }

但是我不确定线程​​和主进程是否同时运行,还是像正常函数一样运行。有人知道正确的方法吗?

zj7887912 回答:如何在C ++中使总是需要新的Input内部循环的单独进程?

使用容器存储所有线程,并在循环后加入所有线程。

void Foo(int i){
    ..... // bunches of operations
}

int main(){
    int i = 0;
    std::vector<std::thread> th1;
    while(i < 5)  // exit flag example
    {
        i++; //incremented i
        th1.emplace_back(Foo,i);  //run the function as separated process that takes new value of i
        // .... other operations
    }
    for (auto &th : th1)
        th.join();  //finish processing the thread
    return 0;
}
,

启动线程时,必须决定线程完成后要做什么。有两种选择:

  1. 您等待它完成(例如,因为您想要一个结果)
  2. 您不需要等待,因为您不需要任何结果,也不需要等到完成后才开始

在情况1中,您需要调用.join()以等待其完成并获得结果。在第2种情况下,您需要调用.detach()来通知C ++库,您无需这样做,并且在线程完成时可以自动释放线程资源。

您必须选择这两个选项之一。如果线程对象被销毁,并且之前没有调用.join.detach,那么您的程序就会出错。

,

并发队列或线程安全队列是我想要的东西。因为我希望线程继续在循环内获取新的输入并以正确的顺序执行该函数,所以我必须实现poppush队列操作。

单线程程序流样本:

Foo(i,q)
    auto out = q.pop()
    print out

Queue q
While()
    i++
    q.push(i)
    Thread1(Foo,i,q) -> execute  // Using vector thread better
    // rest of operation

有关说明,请阅读此tutorial,有关具有多个线程的完整C ++示例,请参阅此github code

本文链接:https://www.f2er.com/3161758.html

大家都在问