CPP如何使主线程等到其他线程在周期中完成

cpp how to make main thread wait until other threads are finished in cycle

本文关键字:线程 周期 何使主 CPP 其他      更新时间:2023-10-16

我正在尝试在不同线程的周期中运行一个CPP代码,并希望我的主线程等到所有其他线程完成。我这样做:

MyClass {
    function(Obj1& res, Obj2& input);
}
AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];
        doSmth1(resvec, inputvec);
        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
        }
        for(int i = 0; i < size; ++i) {
            thpool[i].join();
        }
        doSmth2(resvec);
    }
}

但是代码返回错误的答案,但是,如果我喜欢这个

MyClass {
    function(Obj1& res, Obj2& input);
}
AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];
        doSmth1(resvec, inputvec);
        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
            thpool[i].join();
        }
        doSmth2(resvec);
    }
}

代码返回正确的答案,但没有给出速度的优势。看来我在代码中做错了什么,有人可以帮我吗?谢谢!当我致电方案时会出现问题。

方案中实现的方法

当您连接时,主线程将等到线程结束,因此,如果您在循环中运行,则主线将等待每个线程完成。我认为您要做的是让所有线程脱落,但是当(i == size-1(让他加入时。

只需通过使用Sleep((函数来增加主线程的睡眠时间。