boost::io_service::post线程安全
Is boost::io_service::post thread safe?
从处理程序中发布新的处理程序是线程安全的吗?即,调用io_service::run()
的线程是否可以将新的Handler发布到同一io_service?
感谢
根据文档,从io_service
的单个实例的处理程序内发布处理程序是安全的。
线程安全性
不同对象:安全。
共享对象:安全,但在存在未完成的run()、run_one(),poll()或poll_one()调用导致未定义的行为。
我认为这不是因为下面的代码没有返回3000000,并且我没有看到互斥体同步io_service的内部队列,也没有看到一个无锁队列。
#include <boost/asio/io_service.hpp>
#include <boost/thread.hpp>
#include <boost/thread/detail/thread_group.hpp>
#include <memory>
void postInc(boost::asio::io_service *service, std::atomic_int *counter) {
for(int i = 0; i < 100000; i++) service->post([counter] { (*counter)++; });
}
int main(int argc, char **argv)
{
std::atomic_int counter(0);
{
boost::asio::io_service service;
boost::asio::io_service::work working(service);
boost::thread_group workers;
for(size_t i = 0; i < 10;++i) workers.create_thread(boost::bind(&boost::asio::io_service::run, &service));
boost::thread_group producers;
for (int it = 0; it < 30; it++)
{
producers.add_thread(new boost::thread(boost::bind(postInc,&service,&counter)));
}
producers.join_all();
std::cout << "producers ended" << std::endl;
service.stop();
workers.join_all();
}
std::cout << counter.load();
char c; std::cin >> c;
return 0;
}
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++中的线程安全删除
- 在std::thread中,joinable()然后join()线程安全吗
- 在c++队列中使用pop和visit实现线程安全
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 全局变量 多读取器 一个写入器多线程安全?
- 共享队列的线程安全
- boost::文件系统::recursive_directory_iterator多线程安全
- 以线程安全的方式转换 C/C++ 中时区名称字符串的时区偏移量
- 线程安全运算符<<
- 如何使缓存线程安全
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 提升精神 V2 Qi 语法线程安全吗?
- asio 链对象线程安全吗?
- 线程安全队列 c++
- 提供对不同类型的数据(建议、代码审查)的线程安全访问的类
- 如何以线程安全的方式更改目录?
- 线程安全的引用计数队列C++
- 析构函数和线程安全
- 适用于大型数组的无复制线程安全环形缓冲区