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原理 》一书中的文章,如需观看更多内容,请购买本书。

相关推荐
acocosum1 天前
音视频学习3-视频封装
音视频开发
百度Geek说2 天前
播放器视频后处理实践(一)
音视频开发
音视频牛哥3 天前
从 H.264/H.265 到 H.266:RTSP播放器的跨代际演进
音视频开发·视频编码·直播
GitLqr4 天前
AI洞察 | 混元、昆仑 重塑 3D 世界新方向
计算机视觉·游戏开发·音视频开发
哔哩哔哩技术4 天前
B站第三代转码体系下流式转码测试实践
音视频开发
音视频牛哥5 天前
从「行走」到「思考」:机器人进化之路与感知—决策链路的工程化实践
机器学习·机器人·音视频开发
chenchao_shenzhen8 天前
RK3568嵌入式音视频硬件编解码4K 60帧 rkmpp FFmpeg7.1 音视频开发
ffmpeg·音视频·rk3588·音视频开发·嵌入式开发·瑞芯微rk3568·硬件编解码
码流怪侠10 天前
Google SoundStream音频编解码器技术解析
深度学习·音视频开发
字节跳动视频云技术团队11 天前
基于 DiT 大模型与字体级分割的视频字幕无痕擦除方案,助力短剧出海
aigc·音视频开发·视频编码