boost asio多线程

简介: boost asio多线程

Cnsumer.h

#pragma once
#include <boost/asio/io_service.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <network/EndpointDescription.h>
#include "IArchive.h"
#include "IPlayer.h"
#include "Convert.h"
#include <messages/Messages.h>  // for msg register
#include <Util/Log.h>
#include <thread>
#include <atomic>
//#include "CriticalSection.h"
#include "RdKafkaProducer.h"
#define MAX_THREAD 16
namespace sinftech {
namespace collector {
class Consumer : archive::IPlayer::Listener {
public:
  Consumer(
    archive::IArchive& archive,
  bool& bRun
    );
  ~Consumer();
  void start(const archive::Time& time, const uint8_t& speed);
  void stop();
  void setEndTime(const archive::Time& endTime);
  void ExtractData(const archive::ByteArray& data, const archive::Time& playTime, const int threadIndex);
  void RunThread();
  void JoinThread();
private:
  void onStarted() override;
  void onStopped() override;
  void onDataExtracted(archive::ByteArray&& data, const archive::Time& playTime) override;
private:
  bool& _bRun;
  archive::IArchive& _archive;
  archive::PlayerPtr _player;
  archive::Time _startTime;
  archive::Time _curTime;
  archive::Time _endTime;
  std::thread _threads[MAX_THREAD];
  std::unique_ptr<boost::asio::io_service> _services[MAX_THREAD];
  std::unique_ptr<boost::asio::io_service::work> _works[MAX_THREAD];
  const boost::posix_time::ptime _epoch;
  //CriticalSection _crs;
  //std::set<Target2> _vTargs;
  Target2* _targs[MAX_THREAD];
  const uint8_t S_CLASS_PB_LEVEL = 1;
  const uint32_t _maxSendTarg;
  std::atomic<int> _threadCount;
  std::atomic<int> _targetCount[MAX_THREAD];
  RdKafkaProducer kafkaInstance[MAX_THREAD];
};
}//namespace collector
}//namespace sinftech

Consumer.cpp

#include "stdafx.h"
#include "Consumer.h"
#include <thread>
#include <memory>
#include <boost/bind.hpp>
#include <boost/asio/placeholders.hpp>
#include "Factory.h"
#include "Resource.h"
#include "UniquePtrCast.h"
#include "PlaySerialization.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <zlib/zlib.h>
#include "RdKafkaProducer.h"
#include <json/json.h>
namespace sinftech {
namespace collector {
namespace pt = boost::posix_time;
Consumer::Consumer(archive::IArchive& archive, bool& bRun)
  : _archive(archive)
  , _player(archive::create_player(archive, *this))
  , _bRun(bRun)
  , _threadCount(0)
  , _epoch(boost::gregorian::date(1970, 1, 1))
  , _maxSendTarg(YamlConfig::GetInstance().maxTargets)
{
  for (int i = 0;i < MAX_THREAD;i++) {
    _targs[i] = new Target2[_maxSendTarg];
    memset(_targs[i], 0, sizeof(Target2) * _maxSendTarg);
    _targetCount[i] = 0;
    _services[i] = std::make_unique<boost::asio::io_service>();
    _works[i] = std::make_unique<boost::asio::io_service::work>(*_services[i]);
  }
  RunThread();
}
Consumer::~Consumer() {
  stop();
  for (const auto& service : _services)
    service->stop();
  JoinThread();
  _player.release();
}
void Consumer::RunThread() {
  for (int i = 0;i < MAX_THREAD;i++)
  {
    _threads[i] = std::thread([this, i] {
      try {
        _services[i]->run();
      }
      catch (const std::exception& e) {
        util::log(std::string("playback timer exception: ") + e.what());
        throw;
      }
      catch (...) {
        util::log(std::string("playback timer exception: unknown"));
        throw;
      }
    });
  }
}
void Consumer::JoinThread() {
  for (int i = 0;i < MAX_THREAD;i++)
  {
    if (_threads[i].joinable()) {
      _threads[i].join();
    }
  }
}
void Consumer::setEndTime(const archive::Time& endTime)
{
  _endTime = endTime;
  _player->setEndTime(endTime);
}
void Consumer::start(const archive::Time& time, const uint8_t& speed) {
  //stop();
  auto offsets = _player->timeToOffset(time);
  if (!offsets.empty()) {
  _startTime = time;
    archive::Offset offset = offsets.back();
    _player->start(offset, (archive::SpeedCoefficient&)speed);
  }
}
void Consumer::stop() {
  _player->stop();
  _player.release();
}
void Consumer::onStarted() {
  _bRun = true;
  util::log("onStarted, playbackTime:" + boost::posix_time::to_simple_string(_startTime));
}
void Consumer::onStopped() {
  _bRun = false;
  util::log("onStopped, archive file read finish! playbackTime:" + boost::posix_time::to_simple_string(_curTime));    // _curTime not-a-date-time表示中断!!!
  //PostMessageW(AfxGetApp()->GetMainWnd()->GetSafeHwnd(), COMMAND_A, COMMAND_A, 0);
}
std::string GetStringTime(long long timestamp)
{
  auto milli = timestamp/* + (long long)8 * 60 * 60 * 1000*/;
  auto mTime = std::chrono::milliseconds(milli);
  auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(mTime);
  auto tt = std::chrono::system_clock::to_time_t(tp);
  std::tm *now = std::gmtime(&tt);
  std::string tm = std::to_string(now->tm_year + 1900) + "-";
  tm = tm + std::to_string(now->tm_mon + 1) + "-";
  tm = tm + std::to_string(now->tm_mday) + " ";
  tm = tm + std::to_string(now->tm_hour) + ":";
  tm = tm + std::to_string(now->tm_min) + ":";
  tm = tm + std::to_string(now->tm_sec);
  return tm;
}
void Consumer::onDataExtracted(archive::ByteArray&& data, const archive::Time& playTime) {
  _curTime = playTime;
  _services[_threadCount]->post(std::bind(&Consumer::ExtractData, this, data, playTime, _threadCount.load()));
  _threadCount = ++_threadCount % 4;
}
void Consumer::ExtractData(const archive::ByteArray& data, const archive::Time& playTime, const int threadIndex) {
  auto result = deserialize(data);
  if (!result.message)
    return;
  if (typeid(*result.message) == typeid(msg::display::RefreshTargetDescription))
  {
    msg::display::RefreshTargetDescription* message = reinterpret_cast<msg::display::RefreshTargetDescription*>(&(*result.message));
    Json::Value root;
    root["pos"]["displayId"] = message->displayId;
    root["pos"]["mmsi"] = message->mmsi;
    root["pos"]["id_r"] = message->radarId;
    root["pos"]["state"] = message->predicted ? 2 : 1;
    root["pos"]["quality"] = message->quality;
    root["pos"]["period"] = message->period;
    root["pos"]["geoPnt"]["latitude"] = message->position.latitude();
    root["pos"]["geoPnt"]["longitude"] = message->position.longitude();
    root["pos"]["course"] = message->course;
    root["pos"]["speed"] = message->speed;
    root["pos"]["heading"] = message->heading;
    root["pos"]["len"] = message->length;
    root["pos"]["wid"] = message->width;
    root["pos"]["shiptype"] = message->shipType;
    root["pos"]["flags"] = message->flags;
    root["pos"]["s_class"] = Convert::_fromShipClass(message->shipClass);
    root["pos"]["m_mmsi"] = message->mothershipMmsi;
    root["pos"]["imo"] = message->imo;
    root["pos"]["warning"] = (int)geo::AlarmLevel(message->warningType);
    root["pos"]["id_zone"] = message->warningZoneId;
    root["pos"]["w_time"] = message->warningTime;
    root["pos"]["w_distance"] = message->warningDistance;
    root["pos"]["id"] = message->uniqueId;
    root["pos"]["fleetId"] = message->fleetId;
    root["pos"]["rec_course"] = message->recomendedCourse;
    root["pos"]["rec_speed"] = message->recomendedSpeed;
    root["pos"]["fairwayFlag"] = Convert::_fromFairwayBinding(message->fairwayBinding);
    root["pos"]["Vessel_Name"] = Convert::ws2s(message->vesselName);
    root["pos"]["Vendor_ID"] = message->vendorId;
    root["pos"]["Call_Sign"] = message->callSign;
    root["pos"]["comment"] = Convert::ws2s(message->comment);
    root["pos"]["fairway"] = Convert::ws2s(message->fairway);
    root["sost"] = message->predicted ? 2 : 1;
    root["id"] = message->uniqueId;
    root["lastTm"] = (playTime - _epoch).total_milliseconds();
    std::string strJson = root.toStyledString();
    RdKafkaProducer::GetInstance().PushToKafka(strJson.data(), strJson.size(), KAFUKA_TOPIC::UNION_TARGET_TOPIC);
  }
  if (typeid(*result.message) == typeid(msg::display::RefreshTargetCoordinates))
  {
    msg::display::RefreshTargetCoordinates* message = reinterpret_cast<msg::display::RefreshTargetCoordinates*>(&(*result.message));
    Json::Value root;
    root["pos"]["displayId"] = message->displayId;
    root["pos"]["geoPnt"]["latitude"] = message->position.latitude();
    root["pos"]["geoPnt"]["longitude"] = message->position.longitude();
    root["pos"]["course"] = message->course;
    root["pos"]["speed"] = message->speed;
    root["pos"]["heading"] = message->heading;
    root["pos"]["mmsi"] = message->mmsi;
    root["pos"]["id_r"] = message->radarId;
    root["pos"]["len"] = message->length;
    root["pos"]["period"] = message->period;
    root["pos"]["id"] = message->uniqueId;
    root["pos"]["s_class"] = Convert::_fromShipClass(message->shipClass);
    root["sost"] = message->predicted ? 2 : 1;
    root["lastTm"] = (playTime - _epoch).total_milliseconds();
    root["id"] = message->uniqueId;
    std::string strJson = root.toStyledString();
    RdKafkaProducer::GetInstance().PushToKafka(strJson.data(), strJson.size(), KAFUKA_TOPIC::UNION_TARGET_TOPIC);
    //std::ofstream ofs("data2.txt", std::ios::app);
    //ofs << "displayId:" << message->displayId << ", mmsi:" << message->mmsi
    // << ", lat:" << message->position.latitude()
    // << ", lon:" << message->position.longitude()
    // << ", course:" << message->course
    // << ", heading:" << message->heading
    // << ", speed:" << message->speed
    // << ", time:" << boost::posix_time::to_simple_string(playTime)
    // << std::endl;
    //std::ofstream ofs("data2.txt", std::ios::app);
    //ofs << "displayId:" << message->displayId << ", boost time:" << boost::posix_time::to_simple_string(playTime) << ", stl time:" << GetStringTime(targ.lastTm) << ", count1:" << ++count1 << std::endl;
  }
}
}//namespace collector
}//namespace sinftech
相关文章
|
安全 网络协议 调度
boost中asio网络库多线程并发处理实现,以及asio在多线程模型中线程的调度情况和线程安全。
1、实现多线程方法: 其实就是多个线程同时调用io_service::run         for (int i = 0; i != m_nThreads; ++i)        {            boost::shared_ptr pTh(new boost::thread(   ...
1907 0
|
19天前
|
NoSQL Redis
单线程传奇Redis,为何引入多线程?
Redis 4.0 引入多线程支持,主要用于后台对象删除、处理阻塞命令和网络 I/O 等操作,以提高并发性和性能。尽管如此,Redis 仍保留单线程执行模型处理客户端请求,确保高效性和简单性。多线程仅用于优化后台任务,如异步删除过期对象和分担读写操作,从而提升整体性能。
50 1
|
3月前
|
存储 消息中间件 资源调度
C++ 多线程之初识多线程
这篇文章介绍了C++多线程的基本概念,包括进程和线程的定义、并发的实现方式,以及如何在C++中创建和管理线程,包括使用`std::thread`库、线程的join和detach方法,并通过示例代码展示了如何创建和使用多线程。
68 1
|
3月前
|
Java 开发者
在Java多线程编程中,创建线程的方法有两种:继承Thread类和实现Runnable接口
【10月更文挑战第20天】在Java多线程编程中,创建线程的方法有两种:继承Thread类和实现Runnable接口。本文揭示了这两种方式的微妙差异和潜在陷阱,帮助你更好地理解和选择适合项目需求的线程创建方式。
47 3
|
3月前
|
Java 开发者
在Java多线程编程中,选择合适的线程创建方法至关重要
【10月更文挑战第20天】在Java多线程编程中,选择合适的线程创建方法至关重要。本文通过案例分析,探讨了继承Thread类和实现Runnable接口两种方法的优缺点及适用场景,帮助开发者做出明智的选择。
29 2
|
3月前
|
Java
Java中多线程编程的基本概念和创建线程的两种主要方式:继承Thread类和实现Runnable接口
【10月更文挑战第20天】《JAVA多线程深度解析:线程的创建之路》介绍了Java中多线程编程的基本概念和创建线程的两种主要方式:继承Thread类和实现Runnable接口。文章详细讲解了每种方式的实现方法、优缺点及适用场景,帮助读者更好地理解和掌握多线程编程技术,为复杂任务的高效处理奠定基础。
47 2
|
3月前
|
Java 开发者
Java多线程初学者指南:介绍通过继承Thread类与实现Runnable接口两种方式创建线程的方法及其优缺点
【10月更文挑战第20天】Java多线程初学者指南:介绍通过继承Thread类与实现Runnable接口两种方式创建线程的方法及其优缺点,重点解析为何实现Runnable接口更具灵活性、资源共享及易于管理的优势。
55 1
|
3月前
|
安全 Java 开发者
Java多线程中的`wait()`、`notify()`和`notifyAll()`方法,探讨了它们在实现线程间通信和同步中的关键作用
本文深入解析了Java多线程中的`wait()`、`notify()`和`notifyAll()`方法,探讨了它们在实现线程间通信和同步中的关键作用。通过示例代码展示了如何正确使用这些方法,并分享了最佳实践,帮助开发者避免常见陷阱,提高多线程程序的稳定性和效率。
62 1