Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

106 lines
2.2KB

  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <csignal>
  11. #include <iostream>
  12. #include "Util/logger.h"
  13. #include "Util/util.h"
  14. #include "Util/RingBuffer.h"
  15. #include "Thread/threadgroup.h"
  16. #include <list>
  17. using namespace std;
  18. using namespace toolkit;
  19. //环形缓存写线程退出标记
  20. bool g_bExitWrite = false;
  21. //一个30个string对象的环形缓存
  22. RingBuffer<string>::Ptr g_ringBuf(new RingBuffer<string>(30));
  23. //写事件回调函数
  24. void onReadEvent(const string &str){
  25. //读事件模式性
  26. DebugL << str;
  27. }
  28. //环形缓存销毁事件
  29. void onDetachEvent(){
  30. WarnL;
  31. }
  32. //写环形缓存任务
  33. void doWrite(){
  34. int i = 0;
  35. while(!g_bExitWrite){
  36. //每隔100ms写一个数据到环形缓存
  37. g_ringBuf->write(to_string(++i),true);
  38. usleep(100 * 1000);
  39. }
  40. }
  41. int main() {
  42. //初始化日志
  43. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  44. Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
  45. auto poller = EventPollerPool::Instance().getPoller();
  46. RingBuffer<string>::RingReader::Ptr ringReader;
  47. poller->sync([&](){
  48. //从环形缓存获取一个读取器
  49. ringReader = g_ringBuf->attach(poller);
  50. //设置读取事件
  51. ringReader->setReadCB([](const string &pkt){
  52. onReadEvent(pkt);
  53. });
  54. //设置环形缓存销毁事件
  55. ringReader->setDetachCB([](){
  56. onDetachEvent();
  57. });
  58. });
  59. thread_group group;
  60. //写线程
  61. group.create_thread([](){
  62. doWrite();
  63. });
  64. //测试3秒钟
  65. sleep(3);
  66. //通知写线程退出
  67. g_bExitWrite = true;
  68. //等待写线程退出
  69. group.join_all();
  70. //释放环形缓冲,此时异步触发Detach事件
  71. g_ringBuf.reset();
  72. //等待异步触发Detach事件
  73. sleep(1);
  74. //消除对EventPoller对象的引用
  75. ringReader.reset();
  76. sleep(1);
  77. return 0;
  78. }