在boost asio中strand有什么优势? [英] What is the advantage of strand in boost asio?

查看:28
本文介绍了在boost asio中strand有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习 boost asio 并找出一个名为strand"的类,据我所知.如果只有一个 io_service 与特定的链相关联并通过链发布句柄.

Studying boost asio and find out a class called "strand", as far as I understand. If there are only one io_service associated to a specific strand and post the handle by the strand.

示例(来自 此处)

boost::shared_ptr< boost::asio::io_service > io_service( 
    new boost::asio::io_service
);
boost::shared_ptr< boost::asio::io_service::work > work(
    new boost::asio::io_service::work( *io_service )
);
boost::asio::io_service::strand strand( *io_service );

boost::thread_group worker_threads;
for( int x = 0; x < 2; ++x )
{
    worker_threads.create_thread( boost::bind( &WorkerThread, io_service ) );
}

boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );

strand.post( boost::bind( &PrintNum, 1 ) );
strand.post( boost::bind( &PrintNum, 2 ) );
strand.post( boost::bind( &PrintNum, 3 ) );
strand.post( boost::bind( &PrintNum, 4 ) );
strand.post( boost::bind( &PrintNum, 5 ) );

然后,strand 会为我们序列化处理程序的执行.但是这样做有什么好处?如果我们希望任务成为连载?

Then the strand will serialized handler execution for us.But what is the benefits of doing this?Why don't we just create a single thread(ex : make x = 1 in the for loop) if we want the tasks become serialized?

推荐答案

想象一个系统,其中单个 io_service 管理数百个网络连接的套接字.为了能够并行化工作负载,系统维护了一个调用 io_service::run 的工作线程池.

Think of a system where a single io_service manages sockets for hundreds of network connections. To be able to parallelize workload, the system maintains a pool of worker threads that call io_service::run.

现在这种系统中的大部分操作都可以并行运行.但有些将不得不被序列化.例如,您可能不希望在同一个套接字上同时发生多个写操作.然后每个套接字使用一个链来同步写入:在不同套接字上的写入仍然可以同时发生,而对相同套接字的写入将被序列化.工作线程不必关心同步或不同的套接字,他们只需要获取 io_service::run 交给他们的任何东西.

Now most of the operations in such a system can just run in parallel. But some will have to be serialized. For example, you probably would not want multiple write operations on the same socket to happen concurrently. You would then use one strand per socket to synchronize writes: Writes on distinct sockets can still happen at the same time, while writes to same sockets will be serialized. The worker threads do not have to care about synchronization or different sockets, they just grab whatever io_service::run hands them.

有人可能会问:为什么我们不能只使用互斥锁来代替同步?股线的优点是,如果股线已经在处理,则不会首先安排工作线程.使用互斥锁,工作线程将获得回调,然后在锁定尝试时阻塞,阻止线程执行任何有用的工作,直到互斥锁可用.

One might ask: Why can't we just use mutex instead for synchronization? The advantage of strand is that a worker thread will not get scheduled in the first place if the strand is already being worked on. With a mutex, the worker thread would get the callback and then would block on the lock attempt, preventing the thread from doing any useful work until the mutex becomes available.

这篇关于在boost asio中strand有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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