SDL异步线程互斥锁信号量

mac环境:基于clang,sdl2,pkg-config
简单记录下
SDL_LockMutex :互斥锁(加锁)
SDL_UnlockMutex : 互斥锁(解锁)
SDL_CondWait :等待(线程阻塞)

SDL_cond : 条件变量
SDL_CondSignal:发送通知解阻塞

来自SDL官网的解释SDL_CondWait函数:
This function unlocks the specified mutex and waits for another thread to call SDL_CondSignal() or SDL_CondBroadcast() on the condition variable cond. Once the condition variable is signaled, the mutex is re-locked and the function returns.

The mutex must be locked before calling this function.

This function is the equivalent of calling SDL_CondWaitTimeout() with a time length of SDL_MUTEX_MAXWAIT.

下面直接上简单小例子,简单明了:

#include <SDL2/SDL.h>
#include <stdio.h>
#include <unistd.h>

SDL_bool condition = SDL_FALSE;
SDL_mutex *lock;
SDL_cond *cond;


void thread1(){
    SDL_LockMutex(lock);
    while (!condition) {
        printf("                                         <============等待\n");
        SDL_CondWait(cond, lock);
        printf("                       <===========等到了~_~!!!\n");
    }
    printf("                                          <===========end\n");
    SDL_UnlockMutex(lock);
}
void thread2(){
    SDL_LockMutex(lock);
    printf("                                         <============thread2等待\n");
    SDL_CondWait(cond, lock);
    printf("                                          <===========thread2接收到通知,继续执行~_~!!!\n");
    .....
    printf("                                          <===========thread2 end\n");
    SDL_UnlockMutex(lock);
}

int main(){
    lock = SDL_CreateMutex();
    cond = SDL_CreateCond();
    SDL_Thread * t = SDL_CreateThread(thread2,"thread2",NULL);
    if(!t){
        printf("  %s",SDL_GetError);
        return -1;
    }
    int i ;
    for(i =0;i< 10;i++){
        sleep(3);
        printf("main执行中=====>\n");
    }
    SDL_LockMutex(lock);
    printf("main执行后准备发送signal====================>\n");
    condition = SDL_TRUE;

    SDL_CondSignal(cond);
    SDL_UnlockMutex(lock);

}

运行后结果如下:

$ lock.o
                                         <============thread2等待
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行中=====>
main执行后准备发送signal====================>
                       <===========thread2接收到通知,继续执行~_~!!!
                                          <===========thread2 end
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值