我如何创建可变数量的线程?

问题描述 投票:0回答:1

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

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

c++ multithreading
1个回答
2
投票

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

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.