Just My Life & My Work

[C/C++] SDL 非同步執行任務

想要實現 SDL 和 FFmpeg 非同步方式播放影片,涉及到在一個單獨的線程中解碼影片幀,並在主線程中更新 SDL 視窗。之後做到同時播放影片,還能偵測滑鼠點擊事件。

在 SDL 中,可以使用 SDL_CreateThread 函式創建一個新的線程。以下是一個簡單的例子,演示如何使用 SDL_CreateThread

#include <SDL2/SDL.h>

// 函式將在新線程中運行
int happyThreadFunction(void *data) {
    // 在這裡執行你的線程代碼
    for (int i = 0; i < 5; ++i) {
        printf("Happy thread is running: %d\n", i);
        SDL_Delay(1000); // 模擬一些工作
    }

    return 0;
}

int main(int argc, char *argv[]) {
    // 初始化SDL
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
        fprintf(stderr, "SDL initialization failed: %s\n", SDL_GetError());
        return -1;
    }

    // 創建一個新線程
    SDL_Thread *happyThread = SDL_CreateThread(happyThreadFunction, "MyThread", NULL);

    if (happyThread == NULL) {
        fprintf(stderr, "Thread creation failed: %s\n", SDL_GetError());
        return -1;
    }

    // 主循環
    for (int i = 0; i < 3; ++i) {
        printf("Main thread is running: %d\n", i);
        SDL_Delay(2000); // 模擬一些工作
    }

    // 等待線程結束
    int threadReturnValue;
    SDL_WaitThread(happyThread, &threadReturnValue);

    // 釋放資源
    SDL_Quit();

    return 0;
}

執行結果會陸續列印:

Main thread is running: 0

Happy thread is running: 0

Happy thread is running: 1

Main thread is running: 1

Happy thread is running: 2

Happy thread is running: 3

Main thread is running: 2

Happy thread is running: 4

Program ended with exit code: 0

在這個例子中,happyThreadFunction 是一個在新線程中運行的函式。SDL_CreateThread 創建一個新的線程,並返回一個指向該線程的指針。可以在主循環中繼續執行其他任務,同時新的線程在後台運行。

使用 SDL_WaitThread 函式來等待線程結束。在這個例子中,主循環運行 3 次,每次等待 2 秒,同時 happyThreadFunction 在後台運行,每次等待 1 秒。請注意,SDL_WaitThread 將等待線程完成,並返回線程的返回值。

若不想等,把 SDL_WaitThread 拿掉就好了~😬

參考:ChatGPT。

Comments on: "[C/C++] SDL 非同步執行任務" (1)

  1. 未知 的大頭貼

    […] 若想要同時播放影片,還能偵測滑鼠點擊事件,可參考文章:SDL 非同步執行任務。 […]

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲