簡體   English   中英

Python,非阻塞線程

[英]Python, non-blocking threads

關於Python和異步編碼技術有很多教程等,但是我很難過濾直通結果來找到我需要的東西。 我是Python的新手,所以這沒有幫助。

設定

我目前有兩個看起來像這樣的對象(請原諒我的python格式):

class Alphabet(parent):
    def init(self, item):
        self.item = item

    def style_alphabet(callback):
        # this method presumably takes a very long time, and fills out some properties
        # of the Alphabet object
        callback()


class myobj(another_parent):
    def init(self):
        self.alphabets = []
        refresh()

    def foo(self):
        for item in ['a', 'b', 'c']:
            letters = new Alphabet(item)
            self.alphabets.append(letters)
        self.screen_refresh()

        for item in self.alphabets
            # this is the code that I want to run asynchronously. Typically, my efforts
            # all involve passing item.style_alphabet to the async object / method
            # and either calling start() here or in Alphabet
            item.style_alphabet(self.screen_refresh)

    def refresh(self):
        foo()
        # redraw screen, using the refreshed alphabets
        redraw_screen()

    def screen_refresh(self):
        # a lighter version of refresh()
        redraw_screen()

這個想法是主線程最初用不完整的Alphabet對象繪制屏幕,​​填寫Alphabet對象,在完成時更新屏幕。

我已經嘗試了一些threading.Tread,Queue.Queue甚至是期貨的實現,並且由於某種原因他們要么沒有工作,要么他們已經阻止了主線程。 這樣就不會進行初始抽獎。

我試過的一些異步方法:

class Async (threading.Thread):
    def __init__(self, f, cb):
        threading.Thread.__init__(self)
        self.f  = f
        self.cb = cb

    def run(self):
        self.f()
        self.cb()

def run_as_thread(f):
    # When I tried this method, I assigned the callback to a property of "Alphabet"
    thr = threading.Thread(target=f)
    thr.start()

def run_async(f, cb):
    pool = Pool(processes=1)
    result = pool.apply_async(func=f, args=args, callback=cb)

我最終編寫了一個線程池來處理這種使用模式。 嘗試創建隊列並將引用傳遞給所有工作線程。 從主線程向隊列添加任務對象。 工作線程從隊列中拉出對象並調用這些函數。 在任務完成時向工作線程上的每個任務添加一個事件。 在主線程上保留任務對象列表,並使用輪詢查看UI是否需要更新。 如果需要,可以獲得想象並在任務對象上添加指向回調函數的指針。

我的解決方案受到了我在Google上發現的內容的啟發: http//code.activestate.com/recipes/577187-python-thread-pool/

我不斷改進該設計以添加功能,並為線程,多處理和並行python模塊提供一致的界面。 我的實施是:

https://github.com/nornir/nornir-pools

文檔:

http://nornir.github.io/packages/nornir_pools.html

如果您不熟悉Python並且不熟悉GIL,我建議您搜索Python線程和全局解釋器鎖(GIL)。 這不是一個快樂的故事。 通常我發現我需要使用多處理模塊來獲得不錯的性能。

希望有些幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM