在 C++ 中使用 <thread> 的并发线程 [英] Simultaneous Threads in C++ using <thread>

查看:91
本文介绍了在 C++ 中使用 <thread> 的并发线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在环顾四周,但我不确定为什么会发生这种情况.我已经看到很多关于在 Linux 上使用线程的 Tut,但关于我现在分享的内容并不多.

I have been looking around and I am not sure why is this happening. I've seen lots of Tuts related to using threads on Linux but not much on what I am sharing right now.

代码:

int j = 0;
while(j <= 10)
{
    myThreads[j] = std::thread(task, j);
    myThreads[j].join();
    j+=1;
}

所以我只是想创建 10 个线程并全部执行.任务很简单,处理得也很好,但问题是不是整个线程都在执行.

So I am simply trying to create 10 threads and execute them all. The task is pretty simple and it's been dealt with pretty well but the problem is that not the whole threads are being executed.

它只执行了 1 个线程,它正在等待它完成然后执行另一个等等......

PS:我知道激活这些线程后 main 函数会退出,但我读到了这个,我相信我可以通过多种方式修复它.

PS: I know that the main function will quit after activating those threads but I read about this and I am sure I can fix it in many ways.

所以我想同时执行所有这些线程.

So I want to execute all those threads simultaneously.

非常感谢,马里奥艾达.

Thanks a lot in advance, MarioAda.

推荐答案

您正在启动线程,然后立即加入它们.您需要创建,完成您的工作,然后才加入其他一些循环.此外,您通常将线程放在一个向量中,以便您可以引用/加入它们(您似乎正在这样做,尽管在数组中,因为这是标记为 C++,我鼓励您使用 std::vector 代替).

You are starting threads and then joining them right away. You need to create, do your work and only then join in some other loop. Besides, you generally put the threads in a vector so you can reference/join them (which you seem to be doing, although in an array, since this is tagged C++, I encourage you to use a std::vector instead).

策略与之前的 pthreads 相同:声明一个线程数组,推动它们运行,然后加入.

The strategy is the same as with pthreads before it: your declare an array of threads, push them to run, and then join.

下面的代码来自这里.

#include <thread>
#include <iostream>
#include <vector>

void hello(){
    std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}

int main(){
    std::vector<std::thread> threads;

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

    for(auto& thread : threads){
        thread.join();
    }

    return 0;
}

这篇关于在 C++ 中使用 &lt;thread&gt; 的并发线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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