2014-01-18 34 views
0

我正在生成相當大的圖像,所以我想要讓它一次渲染圖像的不同部分。Python多線程圖像渲染

for startX in xrange(0, width, threadChunk): 
    t = Thread(target = threaded_chunk, args = (thread_num, startX, startX + threadChunk, 1, 0, height, 1)) 
    t.start() 
    t.join() 
    print 'next thread' 
    thread_num += 1 

然而,這似乎並沒有做什麼,我認爲它應該---這在我看來,它等待一個線程纔去到下一個結束。我發現這是因爲我的實際線程函數(threaded_chunk)最後有一個print語句,它通知我線程已經完成。外殼看起來是這樣的,當我運行程序:

Thread 1 completed 
next thread 
Thread 2 completed 
next thread 
# etc 

因此,等待一個運行下一個之前完成。我使用t.join()因爲我想所有的線程後執行最後一步

完成:image.save(imagepath)

有沒有辦法一次運行多個線程,但然後等待,直到所有的線程已經完成執行任務?謝謝!

編輯:我目前的方法適用於Ubuntu的LTS 12.04,但不能在Windows 8.1。

+0

如果我沒有記錯的基礎上,回答A [類似的問題(http://stackoverflow.com/questions/20939299/does-or-doesnt-python-支持多線程)我想,爲了讓多個呈現線程同時運行,您必須確保您發送的函數被直接調用C代碼。也就是說,它應該調用PIL.Image.polygon(或者您使用的任何呈現模塊/操作)而不是threadedchunk,我假設它是您自己使用Python代碼定義的函數。我可能是錯的,但很想聽聽你的結果。 –

回答

2

您應該先啓動所有線程,然後等待它們。你可以這樣說:

threads = [] 
for startX in xrange(0, width, threadChunk): 
    t = Thread(target = threaded_chunk, args = (thread_num, startX, startX + threadChunk, 1, 0, height, 1)) 
    threads.append(t) 
    print 'next thread' 

[t.start() for t in threads] 
[t.join() for t in threads]