
1、流程
(1)先尝试去获取互斥量mutex,如果获取失败,则循环监控locked状态,等待持有锁的线程释放锁
(2)如果获取到互斥量,将locked状态置1,表示锁已被该线程持有,其他线程需要等待,然后释放互斥量,让其他线程有机会进入临界区等待上锁
2、实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
int success;
pthread_lock *thelock = (pthread_lock *)lock;
int status, error = 0;
status = pthread_mutex_lock( &thelock->mut );
success = thelock->locked == 0;
if ( !success && waitflag ) {
while ( thelock->locked ) {
status = pthread_cond_wait(&thelock->lock_released,
&thelock->mut);
}
success = 1;
}
if (success) thelock->locked = 1;
status = pthread_mutex_unlock( &thelock->mut );
if (error) success = 0;
return success;
}
|
以上就是Python获取GIL锁的流程,希望对大家有所帮助。更多Python学习推荐:python教学
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。