是否可以在不等待所有线程完成的情况下执行并行任务(例如 async
)?我想并行化一个定时函数调用,例如一个线程在完成工作之前必须等待一段时间,并在必要时重复它(可能需要几秒钟或几分钟)。还是有其他方法可以实现?
这里是我的示例代码:
#include <iostream>
#include <future>
#include <algorithm>
#include <vector>
class Item
{
public:
int id;
int delayTime; // in ms
int cycles; // number of repetitions
};
class JobManager
{
private:
std::vector<Item> fItems;
public:
JobManager()
{
Item item1, item2;
item1.id = 12;
item1.cycles = 3;
item1.delayTime = 2000;
fItems.push_back(item1);
item2.id = 34;
item2.cycles = 2;
item2.delayTime = 25000;
fItems.push_back(item2);
}
~JobManager() {}
void DoJob(Item& item) {std::cout << "Item " << item.id << "(thread " << std::this_thread::get_id() << ")" << " is doing the job." << std::endl; }
void Start(Item& item)
{
std::this_thread::sleep_for(std::chrono::milliseconds(item.delayTime)); // wait some time
for (int i = 0; i < item.cycles; i++) // repeat the job
{
DoJob(item);
}
}
void Run()
{
std::vector<std::future<void>> futures;
for (auto &it : fItems)
{
futures.push_back(std::async(&JobManager::Start, this, std::ref(it)));
}
// DON'T WANT TO WAIT
//std::for_each(futures.begin(), futures.end(), [](std::future<void> & fut)
//{
// fut.wait();
//});
}
};
int main()
{
JobManager m;
// real method receives a message from network
// so it can be simulated as loop, something like
while(true)
{
m.Run();
Sleep(3000);
}
}
最佳答案
基于 std::thread 的实现应该可以解决问题。
示例
#include <chrono>
#include <thread>
#include <vector>
#include <memory>
#include <cstdio>
#include <cstdlib>
#include <functional>
using std::ref;
using std::hash;
using std::bind;
using std::vector;
using std::thread;
using std::shared_ptr;
using std::make_shared;
using std::chrono::seconds;
using std::chrono::milliseconds;
struct Job
{
int id;
int cycles;
milliseconds delayTime;
};
class JobManager
{
public:
JobManager( void ) : m_jobs( ), m_workers( )
{
m_jobs.push_back( { 12, 3, milliseconds( 2000 ) } );
m_jobs.push_back( { 34, 2, milliseconds( 5000 ) } );
}
virtual ~JobManager( void )
{
for ( auto worker : m_workers )
{
worker->join( );
}
}
void DoJob( Job& job )
{
auto thread_id = hash< thread::id >( )( std::this_thread::get_id( ) );
printf( "Job %i (thread %lu) is doing the job.\n", job.id, thread_id );
}
void Start( Job& job )
{
std::this_thread::sleep_for( job.delayTime );
for ( int cycle_count = 0; cycle_count < job.cycles; cycle_count++ )
{
DoJob( job );
}
}
void Run( void )
{
for ( auto &job : m_jobs )
{
auto worker = std::make_shared< thread >( bind( &JobManager::Start, this, ref( job ) ) );
m_workers.push_back( worker );
}
}
private:
vector< Job > m_jobs;
vector< shared_ptr< thread > > m_workers;
};
int main( int, char** )
{
JobManager manager;
manager.Run( );
std::this_thread::sleep_for( seconds( 10 ) );
return EXIT_SUCCESS;
}
构建
g++ -o example example.cpp -std=c++11 -pthread
引用资料
关于c++ - 在 C++ 中执行并行任务而不等待结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21137978/