简体   繁体   English

我如何分别创建和启动线程

[英]how can i separately create and launch my threads

what i want to do is create some threads and push them into a vector to launch them after some checks. 我想要做的是创建一些线程并将其推入向量中,以便在进行某些检查后启动它们。

so here in my main i want to create theme as follow 所以在这里我主要想创建如下主题

int main()
{

    Pont pont;

    for (int k = 0; k <= 20; k++) {
        std::thread th(crossBridge);
        pont.threadsW.push_back(std::move(th));
    }

    pont.init();
    return 0;
}

and launch theme here: 并在此处启动主题:

void WestToEast()
{
    cout << "préparation du trafic vers l'est \n";
    while (true) {
        std::unique_lock<std::mutex> lock(mut);
        while (!notified2) {
            cond.wait(lock);
        }

        while (!threadsE.empty() && j < 10) {
            j++;

            ""
            "  i want to launch theme here "
            ""
        }
        j = 0;
        notified1 = true;
        notified2 = false;
    }
}

every suggestion is appreciated and also how to join theme once launched and deleted from the vector 每个建议都会受到赞赏,以及一旦启动并从引导程序中删除后如何加入主题

ps: i just posted the concerned part of code ps:我刚刚发布了代码的相关部分

You can populate your vector with default constructed (empty) thread objects. 您可以使用默认构造的(空)线程对象填充向量。

for (int k = 0; k<=20; k++)
    pont.threadsW.push_back({}); // populate vector with empty thread objects

Once you have done your checks, associate each vector object with a thread function. 完成检查后,将每个矢量对象与一个线程函数相关联。

for (auto& th : pont.threadsW)
    th = thread(crossBridge);

You are not really creating a thread and deferring it until it is launched.. Instead, the vector is populated with empty thread objects. 您并不是真正在创建线程并推迟它,直到启动它为止。而是使用空线程对象填充该向量。 The actual thread is created and starts running once you move the new thread into the vector thread object. 一旦将新线程移到矢量线程对象中,就会创建实际线程并开始运行。

When you are done, call join() on each thread object. 完成后,在每个线程对象上调用join()

for (auto& th : pont.threadsW)
    th.join();

If your thread function needs to be in a running state while you are doing your pre-launch checks, additional synchronization is needed where each thread is waiting for the all-clear signal before it can move on. 如果在执行启动前检查时线程功能需要处于运行状态,则需要额外的同步,其中每个线程都在等待全清除信号后才能继续运行。

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

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