2016-05-31 110 views
5

我寫基於FFmpeg媒體播放器,我有一個設計問題。我的代碼使用SDL的SDL_AddTimer函數調用以不規則間隔呈現視頻幀的函數。我的問題是,如果我想在一個視頻結束時(或停止播放)並且另一個視頻開始時執行垃圾回收,我如何確保在隊列中或執行過程中沒有更多定時器,以避免訪問突然被釋放的對象。SDL_AddTimer和線程,清除定時器隊列

+0

至於「在執行過程中」部分,可以用例如將其鎖定互斥。不知道爲什麼在這裏排隊但不活躍的計時器很重要。 – keltar

回答

3

很多不同的方式根據您的具體實現方式解決你的問題。一些基本的思路可以是:

  1. 定義一個布爾值,指定在運行播放器(真=運行,假=不)

  2. 與玩家每次通話前,檢查變量,如果它的假(玩家停止),關閉功能(立即返回)

  3. 然後,你打電話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); 
} 

當然,我不能在一個簡單的計算器上解釋所有的種族條件避免策略。 如果您需要提高性能,您應該準確定義您的代碼的併發問題,並選擇正確的策略。