提供在python應用管理線程和進程的API:Pebble

jopen 10年前發布 | 16K 次閱讀 Pebble Python開發

一個整潔的API,用于在應用程序中管理線程和進程。
Examples

Spawn a function within a thread::

from pebble import thread

def function(foo, bar=0):
    print foo + bar

thrd = thread.spawn(target=function, args=[1], kwargs={'bar':2})
thrd.join()


Most of the functions work as well as decorators::

from pebble import process

@process.spawn(daemon=True)
def function(foo, bar=0):
    print(foo + bar)

proc = function(1, bar=2)
proc.join()


Run a job in a separate process and wait for its results::

from pebble import process

@process.concurrent
def function(foo, bar=0):
    return foo + bar

task = function(1, bar=2)
results = task.get()  # blocks until results are ready


Pools allow to execute several tasks without the need of spawning a new worker for each one of them::

from threading import current_thread
from pebble import thread

def task_done(task):
    results, thread_id = task.get()
    print "Task %s returned %d from thread %s" % (task.id,
                                                  results,
                                                  thread_id)

def do_job(foo, bar=0):
    return foo + bar, current_thread().ident

with thread.Pool(workers=5) as pool:
    for i in range(0, 10):
        pool.schedule(do_job, args=(i, ), callback=task_done)


Check the documentation for more examples.

EXPERIMENTING:

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!