Is a greenthread equal to a “real” thread

吃可爱长大的小学妹 提交于 2019-12-12 10:46:48

问题


I've taken sample code from Unterstanding eventlet.wsgi.server.

from eventlet import wsgi
import eventlet
from eventlet.green import time
import threading

def hello_world(env, start_response):
    print "got request", eventlet.greenthread.getcurrent(), threading.currentThread()
    time.sleep(10)
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Hello, World!\n']

wsgi.server(eventlet.listen(('', 8090)), hello_world)

When I access the web server via different client ip addresses, I can see they are processed in parallel. And with the print in hello_world, I can also that they are processed in two different greenthreads but in same OS thread.

I'm new to Python. I'm curious that if each greenthread ties to an underlying OS thread?


回答1:


Each green thread is tied to exactly one Python thread which is tied to exactly one OS thread. In theory, Eventlet could distribute green threads across several Python threads, and consequently, OS threads, but that is a lot of work for very little benefit since Python code does not execute in parallel on CPython [1].

Rule of thumb: if you want to use multiple cores, choose other language with Python your best bet is to run several processes. Quick way is multiprocessing[2] (in stdlib since 2.6), robust way is os.fork[3][4] manually.

Just a little clarification on terminology: For most popular operating systems, the only way to execute code in parallel is to have multiple OS threads. Strictly speaking, your requests are processed not in parallel but concurrently; precisely because there is only one OS thread. At any given moment in time there is only one green thread executing some code. Incidentally, the same restriction applies to regular Python threads, that's why Eventlet (or other green thread libraries) mostly just work as drop-in replacement and (mostly) do not cause any new unusual bugs.

You may find this answer useful: https://stackoverflow.com/posts/14227272/revisions

[1] http://wiki.python.org/moin/GlobalInterpreterLock
[2] http://docs.python.org/2/library/multiprocessing.html
[3] http://docs.python.org/2/library/os.html#os.fork
[4] https://github.com/jonashaag/bjoern/blob/master/tests/fork.py



来源:https://stackoverflow.com/questions/15287101/is-a-greenthread-equal-to-a-real-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!