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

相关推荐
木西1 天前
短视频图文创作不求人:适合新手的工具推荐
音视频开发
哔哩哔哩技术4 天前
B站多模态精细画质分析模型在 ICCV2025 大赛获得佳绩
音视频开发
鹏多多6 天前
前端音频兼容解决:音频神器howler.js从基础到进阶完整使用指南
前端·javascript·音视频开发
百度Geek说20 天前
百度电商MultiAgent视频生成系统
aigc·音视频开发
字节跳动视频云技术团队22 天前
字节跳动多媒体实验室联合ISCAS举办第五届神经网络视频编码竞赛
人工智能·云计算·音视频开发
x007xyz24 天前
🚀🚀🚀前端的无限可能-纯Web实现的字幕视频工具 FlyCut Caption
前端·openai·音视频开发
CrimsonHu1 个月前
Android高性能音频:写一个云顶S10强音争霸混音器
android·音视频开发
bosscheng1 个月前
0到1理解web音视频从采集到传输到播放系列之《Jessibuca系列篇音视频解封装》
javascript·音视频开发