在For循环中创建一个Thread。 [英] Creating a Thread inside For loop.

查看:1130
本文介绍了在For循环中创建一个Thread。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在for循环中尝试多线程。每次控件进入for循环时,都应该启动一个Thread。在for循环条件结束后,线程应该加入。代码的基本块看起来像,

I have been trying Multi-Threading inside a for loop. Every time the control goes into for loop it should start a Thread. After the for loop condition ends threads should join. The Basic Block of the code will look like,

for()

{

功能(参数) ); //每次输入此for循环时都会运行一个线程函数。

Function(Arguments); // runs a thread function every time entering this for loop.

}

Function.join(); //加入所有主题 

Function.join(); //joining all threads 

我该如何处理?我应该使用Windows API还是std :: thread()? 

how do i proceed with this?.. Should I use Windows API or std::thread()? 

推荐答案

四个线程的可能示例:

 

#include <thread>
#include <array>

. . .

using namespace std;

array<thread, 4> threads;

for( auto & t : threads )
{
	t = thread( [] { cout << "thread started" << endl; } );
}

cout << "waiting..." << endl;

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

cout << "Done." << endl;

 

您可以指定一个函数而不是显示的lambda表达式。对于可变数量的线程,请考虑
vector

 

也可以使用Windows API完成。

 


这篇关于在For循环中创建一个Thread。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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