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