如何创建可变数量的线程? [英] How can I create a variable number of threads?

查看:78
本文介绍了如何创建可变数量的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,该程序将对全局变量进行加减.加法和减法功能将由线程处理.如何持续加/减,直到全局变量达到某个阈值?

I am trying to create a program that will add and subtract from a global variable. The add and subtract features will be handled by threads. How do I continuously add/subtract until the global variable has reached some threshold?

我目前创建了2个线程,一个用于加法,另一个用于减法.但是我的程序每次只会对全局变量加减一次. 我认为我应该创建一个动态线程数组,该数组将不断增长,直到acctBalance达到一定数量为止.我将如何实现这一目标?

I currently have created 2 threads, 1 for adding, another for subtracting. But my program will only add and subtract from the global variable one time each. I figure I should create a dynamic array of threads that will grow until the acctBalance reaches some number. How would I go about accomplishing this?

推荐答案

这里没有什么复杂的事情,只需创建一个向量并向其中添加线程即可.

There isn't anything complicated here, just create a vector and add threads to it:

std::vector<std::thread> threads;
threads.reserve(count);
for (size_t i = 0; i < count; i++)
{
  threads.emplace_back(Add, 0, 15,rand);
}
for (auto& thread : threads)
{
  thread.join();
}

这篇关于如何创建可变数量的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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