您好,登錄后才能下訂單哦!
頭文件
#include "SDL.h"
#include "SDL_thread.h"
int SDL_CondWait(SDL_cond *cond, SDL_mutex *mut);//等待條件變量
SDL_CondWait:釋放傳遞進來的鎖,然后當條件變量滿足的時候,等待其他的線程調用SDL_CondSignal或者SDL_CondBroadcast
改變條件變量cond,然后重新獲取鎖,然后返回。在調用該函數之前必須先調用SDL_LockMutex獲取
鎖。當信號被觸發的時候就返回0,錯誤的時候返回-1
簡而言之,就是釋放鎖,讓其他的線程有機會獲取到鎖,滿足條件的時候,其他的線程會調用SDL_CondSignal或者SDL_CondBroadcast
釋放鎖,并且讓當前的線程繼續執行下去
int SDL_CondSignal(SDL_cond *cond);//喚醒正在等待條件變量發生改變的線程
代碼
typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;??????? //為包的總數
int size;??? //為所有包的大小
SDL_mutex *mutex; //互斥鎖
SDL_cond *cond; //條件變量
} PacketQueue;
我們自己創建的用于構建Packet隊列的數據結構
AVPacketList
A simple linked list for packets.
AVPacket pkt
AVPacketList * next
void packet_queue_init(PacketQueue *q)
{
??? memset(q,0,sizeof(PacketQueue));
??? q->mutex = SDL_CreateMutex();
??? q->cond=SDL_CreateCond();
}
對PacketQueue數據結構進行初始化
用于給PacketQueue數據結構中填入包的函數
int??? packet_queue_put(PacketQueue??? *q,AVPacket??? *pkt)
{
??? AVPacketList??? *pkt1;
??? if(av_dup_packet(pkt)<0)
??? {
??????? return??? -1;??? //檢查是否為NULL,為NULL則自己填充,否則返回-1
??? }
??? pkt1??? =??? av_malloc(sizeof(AVPacketList));//給AVPacketList分配空間
? ?
??? if (!pkt1)
??????? return -1;
??? pkt1->pkt = *pkt;
??? pkt1->next = NULL;
??? SDL_LockMutex(q->mutex); //對PacketQueue進行操作,先鎖定互斥變量
??? if (!q->last_pkt)
??????? q->first_pkt = pkt1;
??? else
??????? q->last_pkt->next = pkt1;
??? q->last_pkt = pkt1;
??? q->nb_packets++;
??? q->size += pkt1->pkt.size;
??? SDL_CondSignal(q->cond); //發送條件信號,方便等待數據的地方喚醒
??? SDL_UnlockMutex(q->mutex); //解鎖
??? return 0;
}
接收數據
static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
{
??? AVPacketList??? *pkt1;
??? int??? ret;
??? SDL_LockMutex(q->mutex);//鎖定mutex
??? for(;;)
??? {
??????? if(quit)
??????? {
??????????? ret??? =-1;
??????????? break;
??????? }
??????? pkt1=q->first_pkt;
??????? if (pkt1) {
??????????? q->first_pkt = pkt1->next;
??????????? if (!q->first_pkt)
??????????????? q->last_pkt = NULL;
??????????? q->nb_packets--;
??????????? q->size -= pkt1->pkt.size;
??????????? *pkt = pkt1->pkt;
??????????? av_free(pkt1);
??????????? ret = 1;
??????????? break;
??????? }
//如果block設置為false,說明不阻塞等待數據包,直接返回
??????? else if (!block) {
??????????? ret = 0;
??????????? break;
??????? }
??????? else {
//等待數據包進入隊列,然后才返回
??????????? SDL_CondWait(q->cond, q->mutex);
??????? }
??? }
??? SDL_UnlockMutex(q->mutex);
??? return ret;
}
SDL_CondWait先檢測是否滿足條件,若不滿足,解鎖mutex,wait,
直至被SDL_CondSignal()函數或者SDL_CondBroadcast()函數通知,
則鎖定mutex并返回
參考
http://blog.sina.com.cn/s/blog_4ae178ba01010fns.html
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。