在C ++中运行两个进程并等待它们完成

时间:2017-06-02 17:09:55

标签: c++ multithreading

我的C ++非常基础,这是我第一次尝试多线程代码。 所以我的数据集非常大,我想我可以通过分离一些功能来减少时间。在Pseudocode下面描述的是我想要的一般概念。

int main(){

    process1();
    process2();

}

process1(){
    base value for recursion
    Builds a forward array
    Once complete - run function combination();
    Recursive call 
}

process2(){
    base value for recursion
    Builds backwards array
    Once complete - run function combination();
    Recursive call
}

combination(){
    when both functions are complete.
    if functions return null then the array is complete
    else add results into a new array.
}

递归呼叫可能是我的难题。是否有一种简单的方法可以实现两个进程必须完成第一次迭代才能运行组合然后再次通过它?

2 个答案:

答案 0 :(得分:4)

这不是运行两个processes,而是运行两个线程

几乎按照定义,流程有自己的virtual address space。因此,如果没有特定的步骤,两个不同的进程就无法共享内存(在Linux上,请参阅mmap(2)& shm_overview(7))。进程可以有多个线程,它们共享相同的虚拟地址空间,每个线程在该虚拟地址空间中都有自己的call stack

这个pthread tutorial教授关于P线程的有趣概念(你可以很容易地适应C++11 threads

您可能想了解有关condition variablesmutexes的更多信息,因为您应该关注synchronization

答案 1 :(得分:3)

  

是否有一种简单的方法可以实现两个进程必须完成第一次迭代才能运行组合,然后再次进行组合?

一个信号。您希望线程等待信号。也称为condition variables。 (Posix

多线程有很多资源,而且你一定要学习的技术(目前多核是标准的)。

Strategized Locking, Thread-safe Interface, and scoped Locking

Half-Sync/Half-ASync(描述并发队列)

Atomicity Policies using Design Patterns(描述生产者/消费者,读/写政策)。