python如何处理线程锁定/上下文切换? [英] How does python handle thread locking / context switching?

查看:129
本文介绍了python如何处理线程锁定/上下文切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观看了关于GIL的精彩演讲,以及如何在解释器中运行时一次只能运行一个单线程.似乎python在线程之间切换也不是很聪明.

I watched an excellent presentation on the GIL, and how when running in the interpreter only 1 single thread can run at a time. It also seemed that python is not very intelligent about switching between threads.

如果我正在对仅在解释器中运行的某些操作进行线程化,而这对CPU的占用不是特别大,并且我使用了线程锁,则在此相对较短的解释器绑定操作中一次只能运行1个线程,这会否锁定实际上会使运行速度变慢吗?与此相反,如果不需要该锁并且所有线程都可以同时运行.

If i am threading some operation that only runs in the interpreter, and it is not particularly CPU heavy, and I use a thread lock where only 1 thread can run at a time for this relatively short interpreter-bound operation, will that lock actually make anything run slower? as opposed to if the lock were not necessary and all threads could run concurrently.

如果除1个线程外的所有线程均被锁定,python解释器是否会知道不进行上下文切换?

If all but 1 threads are locked, will the python interpreter know not to context switch?

通过使运行速度变慢",我的意思是,如果python将上下文切换到一堆锁定的线程,那么即使线程实际上未运行,这也可能会降低性能

by 'making things run slower' I mean if python is context switching to a bunch of locked threads, that will (maybe) be a performance decrease even if the threads don't actually run

推荐答案

python对于线程之间的切换不是很聪明

python is not very intelligent about switching between threads

Python线程以某种方式工作:-)

Python threads work a certain way :-)

如果我使用一个线程锁,一次只能运行1个线程...该锁实际上会使任何东西运行都变慢

if I use a thread lock where only 1 thread can run at a time... will that lock actually make anything run slower

Err,不,因为没有其他可运行的东西,所以其他任何事情都不会变慢.

Err, no because there is nothing else runnable, so nothing else could run slower.

如果除1个线程外的所有线程均被锁定,python解释器是否会知道不进行上下文切换?

If all but 1 threads are locked, will the python interpreter know not to context switch?

是的.内核知道哪些线程是可运行的.如果没有其他线程可以运行,则从逻辑上讲(就该线程而言),python解释器不会上下文切换离开唯一可运行的线程.线程不知道何时将其从线程中移开(怎么可能,它没有运行).

Yes. The kernel knows which threads are runnable. If no other threads can run then logically speaking (as far as the thread is concerned) the python interpreter won't context switch away from the only runnable thread. The thread doesn't know when it has been switched away from (how can it, it isn't running).

这篇关于python如何处理线程锁定/上下文切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆