序列化部分工作- boost::asio
Serializing part of work - boost::asio
void wt(shared_ptr<io_service> io_servicee)
{
io_servicee->run();
}
void calculateAndReturn(int myNumber, shared_ptr<vector<int> > vectorOfResults)
{
/*
* Here will be a lot of pararel computing (first part)...
*/
int result = myNumber;
/* This part (second part) below I want to be executed sequentially depending on the number of thread.
* Thread which has myNumber == 1 should be first, second should be thread with
* myNumber == 2, third with myNumber == 3 etc.
*
*/
mt.lock();
vectorOfResults->push_back(result);
mt.unlock();
}
int main()
{
shared_ptr< io_service > io_servicee(new io_service);
shared_ptr< io_service::work > work(new io_service::work( *io_servicee ));
shared_ptr<vector<int> > vectorOfSums(new vector<int>);
thread_group worker_threads;
for( int x = 0; x < 4; ++x )
{
worker_threads.create_thread(bind( &wt, io_servicee ));
}
for( int x = 0; x < 4; ++x )
{
io_servicee->post(bind( &calculateAndReturn, x, vectorOfSums));
}
work.reset();
worker_threads.join_all();
for ( int i = 0; i < vectorOfSums->size(); i++)
{
cout << (*vectorOfSums)[i] << endl;
}
}
我想序列化calculateAndReturn函数的一部分。它应该是这样的:
First part of thread 1 ------->
First part of thread 2 -------> -- Second part of thread 1 --> second part of thread2...
/
.... /
/
First part of thread n ------->/
我不想在主函数中使用strand,而不是在calculateAndReturn的第二部分之前。有什么优雅的解决方案吗?
如果您在单个进程中执行此操作,我建议使用OpenMP。典型的例子:
#include <omp.h>
#define N 1000
#define CHUNKSIZE 100
main ()
{
int i, chunk;
float a[N], b[N], c[N];
/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i * 1.0;
chunk = CHUNKSIZE;
#pragma omp parallel for shared(a,b,c,chunk) private(i) schedule(static,chunk)
for (i=0; i < n; i++)
c[i] = a[i] + b[i];
}
在gnu: install libgomp, build
g++ -fopenmp -lgomp source.cpp
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 如何在 Boost.Asio 中使用 Zero-copy sendmsg/receive
- C++ Boost::asio串行通信与Arduino无法写入
- 如何使用 Boost Asio 在 Android 上获取我的本地 udp IP 地址?
- boost::asio UDP 广播客户端仅接收"fast"数据包
- 执行时使用 boost::asio::d eadline_timer 时出错
- Boost.Asio/OpenSSL HTTPS GET certificate trouble
- C++ boost::asio::ip::tcp::acceptor 有时不接受连接器?
- boost::asio data owning `ConstBufferSequence`
- 如何替换此示例代码片段中已弃用的handler_type_t或 boost::asio::handler_type?
- 将 boost 序列化对象的 asio::streambuf 表示转换为 Beast 的 DynamicBody req.body()
- 如何将boost::asio::d eadline_timer 与Qt一起使用?
- 将更高的优先级设置为 boost::asio 线程处理进程
- Async_read_until限制读取的字节大小(Boost::asio)
- Boost Asio - boost::bind 导致程序崩溃
- 使用Asio(Boost)通过网络发送灵活的数据量