详解WebRTC rtc::Thread实现

rtc::Thread介绍

rtc::Thread类不仅仅实现了线程这个执行器(比如posix底层调用pthread相关接口创建线程,管理线程等),还包括消息队列(message_queue)的实现,rtc::Thread启动后就作为一个永不停止的event loop,没有任务待执行就阻塞等待,添加任务后就唤醒event loop,去执行任务,周而复始,直到调用stop退出event loop,退出线程(线程join)。

在WebRTC内部,可以将消息队列等同于event loop,消息队列为空,就进行阻塞等待。


class RTC_LOCKABLE Thread : public MessageQueue {

Thread关键接口

public:// Starts the execution of the thread.bool Start(Runnable* runnable = nullptr);// Tells the thread to stop and waits until it is joined.// Never call Stop on the current thread.  Instead use the inherited Quit// function which will exit the base MessageQueue without terminating the// underlying OS thread.virtual void Stop();virtual void Send(const Location& posted_from,MessageHandler* phandler,uint32_t id = 0,MessageData* pdata = nullptr);// Convenience method to invoke a functor on another thread.  Caller must// provide the |ReturnT| template argument, which cannot (easily) be deduced.// Uses Send() internally, which blocks the current thread until execution// is complete.// Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,// &MyFunctionReturningBool);// NOTE: This function can only be called when synchronous calls are allowed.// See ScopedDisallowBlockingCalls for details.template <class ReturnT, class FunctorT>ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {FunctorMessageHandler<ReturnT, FunctorT> handler(std::forward<FunctorT>(functor));InvokeInternal(posted_from, &handler);return handler.MoveResult();}// ProcessMessages will process I/O and dispatch messages until://  1) cms milliseconds have elapsed (returns true)//  2) Stop() is called (returns false)bool ProcessMessages(int cms);protected:// Blocks the calling thread until this thread has terminated.void Join();

MessageQueue关键接口

public:
virtual void Quit();// Get() will process I/O until:
//  1) A message is available (returns true)
//  2) cmsWait seconds have elapsed (returns false)
//  3) Stop() is called (returns false)
virtual bool Get(Message* pmsg,int cmsWait = kForever,bool process_io = true);virtual void Post(const Location& posted_from,MessageHandler* phandler,uint32_t id = 0,MessageData* pdata = nullptr,bool time_sensitive = false);
virtual void PostDelayed(const Location& posted_from,int cmsDelay,MessageHandler* phandler,uint32_t id = 0,MessageData* pdata = nullptr);
virtual void PostAt(const Location& posted_from,int64_t tstamp,MessageHandler* phandler,uint32_t id = 0,MessageData* pdata = nullptr);virtual void Dispatch(Message* pmsg);
virtual void ReceiveSends();protected:
void WakeUpSocketServer();MessageList msgq_ RTC_GUARDED_BY(crit_);
PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);

线程启动Start

调用Start接口启动底层线程,同时进入一个永不停止的event loop(除非调用Stop接口)
流程如下:
Start->pthread_create->PreRun->Run

void Thread::Run() {ProcessMessages(kForever);
}

在这里插入图片描述
最终通过Get接口获取消息去执行(Dispatch),Get获取不到消息就是进入阻塞状态(wait),等待有消息后被唤醒。
在这里插入图片描述

线程消息队列处理消息的流程ProcessMessage

  • 1、处理从其他线程发送的要在本线程去执行的消息,即同步调用
    在这里插入图片描述

接收者线程处理流程:
在这里插入图片描述在这里插入图片描述

发送者线程流程:
在这里插入图片描述

  • 2、处理延迟消息(存储在优先级队列)
    延迟消息是通过PostDelayed和PostAt接口调用然后push到优先级队列中(dmsgq_,小根堆)
    在这里插入图片描述

  • 3、异步消息(存储在普通队列里)
    延迟消息是通过Pos接口调用然后push到普通队列中(msgq_)
    在这里插入图片描述

任务提交方式(Invoke/Post)

webrtc内部消息其实是对待执行任务的封装,消息和任务可以认为是一个意思

消息要继承MessageHandler,实现OnMessage

class MessageHandler {public:virtual ~MessageHandler();virtual void OnMessage(Message* msg) = 0;protected:MessageHandler() {}private:RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandler);
};

因为执行消息,实际上就是执行OnMessage(详见Dispatch接口实现)
在这里插入图片描述

上一章节其实已经把三种任务提交方式介绍过了
1、同步阻塞调用(Send,Invoke)
Invoke其实最终也是调用Send,Invoke是个函数模版,可以非常方便在目标执行线程执行函数然后获得返回值,Invoke实现如下:

  // Convenience method to invoke a functor on another thread.  Caller must// provide the |ReturnT| template argument, which cannot (easily) be deduced.// Uses Send() internally, which blocks the current thread until execution// is complete.// Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,// &MyFunctionReturningBool);// NOTE: This function can only be called when synchronous calls are allowed.// See ScopedDisallowBlockingCalls for details.template <class ReturnT, class FunctorT>ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {FunctorMessageHandler<ReturnT, FunctorT> handler(std::forward<FunctorT>(functor));InvokeInternal(posted_from, &handler);return handler.MoveResult();}void Thread::InvokeInternal(const Location& posted_from,MessageHandler* handler) {TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file_and_line",posted_from.file_and_line(), "src_func",posted_from.function_name());Send(posted_from, handler);
}

调用方式举例:

bool result = thread.Invoke<bool>(RTC_FROM_HERE, &MyFunctionReturningBool);

2、异步非阻塞延迟调用
PostDelayed和PostAt

3、异步非阻塞调用
Post

线程退出Stop

void Thread::Stop() {MessageQueue::Quit();Join();
}void MessageQueue::Quit() {AtomicOps::ReleaseStore(&stop_, 1);WakeUpSocketServer();
}void Thread::Join() {if (!IsRunning())return;RTC_DCHECK(!IsCurrent());if (Current() && !Current()->blocking_calls_allowed_) {RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "<< "but blocking calls have been disallowed";}#if defined(WEBRTC_WIN)RTC_DCHECK(thread_ != nullptr);WaitForSingleObject(thread_, INFINITE);CloseHandle(thread_);thread_ = nullptr;thread_id_ = 0;
#elif defined(WEBRTC_POSIX)pthread_join(thread_, nullptr);thread_ = 0;
#endif
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/447706.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【C++游戏开发-01】推箱子

C游戏开发 文章目录 C游戏开发[TOC](文章目录) 前言一、逻辑分析1.1地图实现1.2人物的移动1.2.1小人移动1.2.2其他移动 1.3墙壁的碰撞1.4箱子的推动1.4.1什么时候推箱子1.4.2什么情况可以推箱子 1.5胜利的判断1.6卡关的处理1.7关卡的切换 二、DEMO代码2.1游戏框架2.2各功能函数…

刨析数据结构(二)

&#x1f308;个人主页&#xff1a;小田爱学编程 &#x1f525; 系列专栏&#xff1a;数据结构————"带你无脑刨析" &#x1f3c6;&#x1f3c6;关注博主&#xff0c;随时获取更多关于数据结构的优质内容&#xff01;&#x1f3c6;&#x1f3c6; &#x1f600;欢迎…

【音视频 ffmpeg 】直播推流QT框架搭建

简介&#xff1a; 【音视频 ffmpeg 】直播推流QT框架搭建 3个线程 一个做视频解码一个做音频解码一个做复用推流 视频解码线程展示 #include "videodecodethread.h" VideodecodeThread::VideodecodeThread(QObject *parent):QThread(parent) {avdevice_register_a…

【前端web入门第三天】01 css定义和引入方式 四种标签选择器

文章目录: 1.css 定义 2.css引入方式 3.选择器 3.1 标签选择器 3.2 类选择器 3.3 id选择器 3.4 通配符选择器 4. 画盒子 1.css 定义 层叠样式表(Cascading Style Sheets&#xff0c;缩写为CSS)&#xff0c;是一种样式表语言&#xff0c;用来描述HTML文档的呈现&#xff08;美…

一键部署幻兽帕鲁服务器免费一年方案

一、背景介绍 简单讲一下历程&#xff0c;幻兽帕鲁从在1月19日上线&#xff0c;24小时内在线人数峰值便突破200万&#xff0c;作为2024年第一款现象级游戏&#xff0c;《幻兽帕鲁》上线后&#xff0c;由于人数太多&#xff0c;频现服务器过载导致游戏卡顿掉线的情况。为了能够…

前端入门第三天

目录 一、CSS定义 二、CSS引入方式 三、基础选择器 1.标签选择器 2.类选择器 3.id选择器 4.通配符选择器 5.画盒子 四、文字控制属性 1.字体大小 2.字体粗细 3.字体倾斜 4.行高 1.行高-垂直居中 5.字体族 6.font复合属性 7.文本缩进 8.文本对齐方式 1.水平对…

C#,打印漂亮的贝尔三角形(Bell Triangle)的源程序

以贝尔数为基础&#xff0c;参考杨辉三角形&#xff0c;也可以生成贝尔三角形&#xff08;Bell triangle&#xff09;&#xff0c;也称为艾特肯阵列&#xff08;Aitkens Array&#xff09;&#xff0c;皮埃斯三角形&#xff08;Peirce Triangle&#xff09;。 贝尔三角形的构造…

Pycharm Community 配置调试Behave

前提&#xff1a;python小白&#xff0c;临时搞python项目&#xff0c;公司限制使用Pycharm版本&#xff0c;故只能使用社区版&#xff0c;然而官方有明确说明&#xff1a;只有Professional版支持Behave。故研究了半天才整清楚社区版调试Behave的设置 没有进行下面的步骤之前&…

Unity | 渡鸦避难所-9 | 角色名字及血条等信息

1 效果预览 游戏中角色的名字和血条是非常重要的元素&#xff0c;它们可以帮助玩家了解角色的身份和状态。在 Unity 中&#xff0c;可以使用 UGUI 来实现这些功能 2 实现方案 1 画布 (Canvas) 画布 (Canvas) 组件表示进行 UI 布局和渲染的抽象空间。所有 UI 元素都必须是附加…

Keil软件某些汉字输出乱码,0xFD问题,51单片机

1. 问题 keil软件输入某些汉字的时候会输出乱码&#xff0c;例如&#xff1a;升、 数 2. 原因 keil软件会忽略0xFD。 升的GB2312编码为 0xc9fd&#xff0c;keil解析为0xc9数的GB2312编码为 0xcafd&#xff0c;keil解析为0xca 关于Keil软件中0xFD问题的说明 3. 解决方案1 …

协作办公开源神器:ONLYOFFICE

目录 前言ONLYOFFICE为什么选择ONLYOFFICE强大的文档编辑功能多种协作方式多人在线协同支持跨端多平台连接器安全性极高本地部署 ONLYOFFICE 8.0版本震撼来袭可填写的 PDF 表单显示协作用户头像更新插件界面设计更快更强大 总结 前言 近几年来&#xff0c;随着互联网技术的不断…

gilab 展示测试用例结果详情页面

Python 此示例使用带有 --junitxmlreport.xml 标志的 pytest 将输出格式化为 JUnit 报告 XML 格式&#xff1a;gitlab 会自动去解析report.xml 这个文件&#xff0c;并且将每个case的测试结果展示在gitlab中pytest:stage: testscript:- pytest --junitxmlreport.xmlartifacts:w…