Асинхронность множества потоков с++
подскажите, как создать динамический массив для асинхронных потоков, чтобы функции вложенные в потоки выполнялись одновременно. В примере указаны 2 потока с явным объявлением, а необходимо создать и запустить заданное количество потоков.
#include <future>
#include <iostream>
#include <thread>
int main(int argc, char* argv[])
{
// Явное указание типа возвращаемого объекта
std::future<void> asyncFuture1 = std::async(std::launch::async, []() {
for(int i=0; i < 15; i++)
{
std::cout << i;
}
});
// Автоматический тип возвращаемого объекта
auto asyncFuture2 = std::async(std::launch::async, []() {
for(int i=0; i < 15; i++)
{
std::cout << i;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
});
return 0;
}
При попытке создать динамический массив выдает ошибку преобразования типа
auto* threadsList{new thread[q]};
for (int i = 0; i < q; i++) {
threadsList[i] = async(readLine,str);
//cout << typeof(threadsList[i]);
}
for (int i = 0; i < q; i++) {
threadsList[i].get();
}
Ответы (1 шт):
Автор решения: Harry
→ Ссылка
Так вас устроит? Если надо именно через async?
#include <future>
#include <iostream>
#include <thread>
#include <sstream>
#include <chrono>
using namespace std;
auto func = []() {
for(int i = 0; i < 20; ++i)
{
ostringstream os;
os << this_thread::get_id() << "\n";
cout << os.str();
this_thread::sleep_for(chrono::milliseconds(100));
}
};
int main(int argc, char* argv[])
{
vector<future<void>> futures;
for(int i = 0; i < 20; ++i)
futures.emplace_back(async(launch::async, func));
for(int i = 0; i < 20; ++i)
futures[i].get();
}
То же через thread:
int main(int argc, char* argv[])
{
vector<thread> threads;
for(int i = 0; i < 20; ++i)
threads.emplace_back(func);
for(int i = 0; i < 20; ++i)
threads[i].join();
}
Если очень надо именно массив:
int main(int argc, char* argv[])
{
thread threads[20];
for(int i = 0; i < 20; ++i)
threads[i] = thread(func);
for(int i = 0; i < 20; ++i)
threads[i].join();
}
