我如何使线程顺序运行而不是并发? [英] How do I make threads run sequentially instead of concurrently?

查看:147
本文介绍了我如何使线程顺序运行而不是并发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我想让每个线程在上一个线程完成之前不会开始运行,是否有一个标志,例如 thread.isRunning()

For example I want each thread to not start running until the previous one has completed, is there a flag, something like thread.isRunning()?

#include <iostream>
#include <vector>
#include <thread>
using namespace std;

void hello() {
    cout << "thread id: " << this_thread::get_id() << endl;
}

int main() {

    vector<thread> threads;

    for (int i = 0; i < 5; ++i)
        threads.push_back(thread(hello));


    for (thread& thr : threads)
        thr.join();

    cin.get();
    return 0;
}



我知道线程是并发运行的,如果我想控制顺序?

I know that the threads are meant to run concurrently, but what if I want to control the order?

推荐答案

如果我们需要第二个线程开始在第一个线程之后运行

If we need the second thread start to run after the first one is completed, is a thread really needed?

对于解决方案我想尝试设置一个全局标志,设置第一个线程中的值,并且当启动第二个线程,检查标志首先应该工作。

For solution I think try to set a global flag, the set the value in the first thread, and when start the second thread, check the flag first should work.

这篇关于我如何使线程顺序运行而不是并发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆