ST协程切换回调介绍—StateThreads协程源码分析

StateThreads 提供了一个协程切换回调功能,当切走 协程的时候 会执行 _st_this_vp.switch_out_cb() 函数,到恢复协程的时候 会执行 _st_this_vp.switch_in_cb() 函数。

我们可以通过 st_set_switch_in_cb()st_set_switch_out_cb() 注册这两个回调函数,这样可以对协程切换进行 hook 操作。

我们修改一下 lookupdns.c 文件,如下:

arduino 复制代码
//添加头文件
#include "../common.h"
arduino 复制代码
//新增回调函数
int switch_count = 0;
void my_switch_in_cb(void){
    _st_thread_t *thread = st_thread_self();
    printf("switch_in thread %p \n", thread);
    switch_count++;
};
void my_switch_out_cb(void){
    _st_thread_t *thread = st_thread_self();
    printf("switch_out thread %p \n", thread);
    switch_count++;
};
scss 复制代码
//注册回调函数
st_set_switch_in_cb(my_switch_in_cb);
st_set_switch_out_cb(my_switch_out_cb);

完整的代码可以在 GitHub 进行下载。运行命令 以及 结果如下:

复制代码
lookupdns srs.xianwaizhiyin.net ffmpeg.xianwaizhiyin.net www.xianwaizhiyin.net

可以看到,一共进行了 6 次协程切换。不过 switch_out 的日志 比 switch_in 多了几条,不是应该一样的吗?

这个我觉得是这个回调的机制不太完成,具体的原因请阅读《协程是什么时候开始运行》里面对 st_thread_exit() 函数的分析。


协程切换回调 的原理是这样的,我们注册回调函数,只是设置两个变量 _st_this_vp.switch_in_cb_st_this_vp.switch_out_cb,这两个变量是 函数指针 来的。然后在 _ST_SWITCH_CONTEXT() 的时候,就会调用这两次回调函数。如下:


本文是《 SRS原理 》一书中的文章,如需观看更多内容,请购买本书。

相关推荐
散歌2 天前
小程序 RecorderManager 录音分贝解析及来电检测
微信小程序·音视频开发
爱吃猪排3 天前
用AI监听语音通话的方案和实践
人工智能·音视频开发
mortimer5 天前
半开源语音克隆神器 MegaTTS3:安装难、用起来更难?手把手从安装到使用
开源·github·音视频开发
AJi5 天前
Android音视频框架探索(二):Binder——系统服务的通信基础
android·ffmpeg·音视频开发
音视频牛哥15 天前
nginx-rtmp-module之ngx_rtmp.c代码详解
音视频开发·视频编码·直播
音视频牛哥15 天前
ngx_rtmp_flv_module.c — FLV文件处理模块设计与分析
音视频开发·视频编码·直播
音视频牛哥15 天前
音视频新人如何快速上手nginx-rtmp-module
音视频开发·视频编码·直播
是阿鸽呀15 天前
【音视频开发】10. 使用 FFmpeg API 编码 ADTS 音频流
音视频开发
音视频牛哥18 天前
Android平台毫秒级低延迟HTTP-FLV直播播放器技术探究与实现
音视频开发·视频编码·直播
路漫漫心远20 天前
音视频学习笔记十五——渲染与滤镜之GPUImage滤镜链
音视频开发