我正在基于FFmpeg编写媒体播放器,但遇到了设计问题。我的代码使用SDL的SDL_AddTimer函数在不规则的时间间隔内调用渲染视频帧的函数。我的问题是,如果我想在一个视频结束(或播放停止)并开始另一个视频时执行垃圾回收,如何确保没有更多的计时器在队列中或正在执行中,以避免访问突然被释放的对象。
定义一个布尔值,指定播放器是否正在运行(true = 正在运行,false = 停止)
在与播放器相关的每个调用之前,检查该变量是否为假(播放器已停止),如果是,关闭函数(立即返回)
然后,您调用removeTimer
并将变量设置为false以关闭播放器。
addTimer
是创建线程的函数,所以有时会出现竞争条件(您称之为“执行中间”)。这是使用线程时的主要问题之一。#include <pthread.h>
#include <stdbool.h>
pthread_mutex_t mutex;
bool isRunning;
int timerID;
void timerCallback(){
// do some computations
pthread_mutex_lock(&mutex);
// that critical section, defined here will never
// (thank to the mutex) occur at the same time at
// the critical section in the close method
if(isRunning){
// do critical calls
}
else{
// do nothing
}
pthread_mutex_unlock(&mutex);
// do some other computations
}
void init(){
pthread_mutex_init(&mutex, NULL);
isRunning = true;
startTimers();
}
void close(){
pthread_mutex_lock(&mutex);
// that critical section, defined here will never
// (thank to the mutex) occur at the same time at
// the critical section in the timerCallback method
SDL_RemoveTimer(timerID);
isRunning = false;
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
}