温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中获取和释放GIL

发布时间:2021-04-27 16:52:53 来源:亿速云 阅读:346 作者:Leah 栏目:编程语言

这篇文章给大家介绍怎么在python中获取和释放GIL,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

python的五大特点是什么

python的五大特点:1.简单易学,开发程序时,专注的是解决问题,而不是搞明白语言本身。2.面向对象,与其他主要的语言如C++和Java相比, Python以一种非常强大又简单的方式实现面向对象编程。3.可移植性,Python程序无需修改就可以在各种平台上运行。4.解释性,Python语言写的程序不需要编译成二进制代码,可以直接从源代码运行程序。5.开源,Python是 FLOSS(自由/开放源码软件)之一。

1、说明

线程对GIL的操作本质上就是通过修改locked状态变量来获取或释放GIL。

2、获取GIL实例

线程在其他线程已经获取GIL的时候,需要通过pthread_cond_wait()等待获取GIL的线程释放GIL。

/*获取GIL*/
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 ); /*先获取mutex, 获得操作locked变量的权限*/
    success = thelock->locked == 0;
    if ( !success && waitflag ) { /*已有线程上锁,*/
        while ( thelock->locked ) {
            /*通过pthread_cond_wait等待持有锁的线程释放锁*/
            status = pthread_cond_wait(&thelock->lock_released,
                                       &thelock->mut);
        }
        success = 1;
    }
    if (success) thelock->locked = 1; /*当前线程上锁*/
    status = pthread_mutex_unlock( &thelock->mut ); /*解锁mutex, 让其他线程有机会进入临界区等待上锁*/
    if (error) success = 0;
    return success;
}

3、释放GIL实例

特别注意最后一步, 通过pthread_cond_signal()通知其他等待(pthread_cond_wait())释放GIL的线程,让这些线程可以获取GIL。

/*释放GIL*/
void PyThread_release_lock(PyThread_type_lock lock)
{
    pthread_lock *thelock = (pthread_lock *)lock;
    int status, error = 0;
    status = pthread_mutex_lock( &thelock->mut ); /*通过mutex获取操作locked变量的权限*/
    thelock->locked = 0; /*实际的释放GIL的操作, 就是将locked置为0*/
    status = pthread_mutex_unlock( &thelock->mut ); /*解锁mutex*/
    status = pthread_cond_signal( &thelock->lock_released ); /*这步非常关键, 通知其他线程当前线程已经释放GIL*/
}

关于怎么在python中获取和释放GIL就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI