天天看點

twisted 線程裡的幾個函數

twisted裡是通過回調機制來實作類似于多線程,意思是防止程式的運作由于等待某項任務的完成而陷入阻塞停滞,提高整體運作的效率。

from twisted.internet import reactor

1. reactor.callFromThread

Method callFromThread:

Cause a function to be executed by the reactor thread.

Use this method when you want to run a function in the reactor's thread from another thread. Calling callFromThread should wake up the main thread (where reactor.run() is executing) and run the given callable in that thread.

If you're writing a multi-threaded application the callable may need to be thread safe, but this method doesn't require it as such. If you want to call a function in the next mainloop iteration, but you're in the same thread, use callLater with a delay of 0.

此方法是本身是mainloop的線程,用reactor.stop()可以終止它。也可以reactor.callFromThread(reactor.stop)來終止它。但是這個方法會阻塞到主循環。

  1. #coding=utf-8
  2. from twisted.internet import reactor
  3. import time
  4. def tt(i,j):
  5.     while 1:
  6.         print i,'---------------',j
  7.         time.sleep(1)
  8. reactor.callFromThread(tt,1,1)
  9. reactor.callFromThread(tt,4,2)

上面代碼運作的結果是無限的列印1-------------------1,這個說明了主循環被阻塞住。

2. reactor.callInThread

Method callInThread:

Run the callable object in a separate thread.

此方法是建立獨立的線程,用reactor stop方法無法停止它。這裡涉及到一個線程池的概念

reactor.suggestThreadPoolSize(15)來設定線程池的大小,預設是最小是5,最大是10.如果在預設情況下

3. from twisted.internet import threads

threads.deferToThread(function),和callInThread一樣,差別隻是 deferToThread 可以傳回一個deferred對象,進而允許你設定回調函數。

了解不夠,參考下面

http://www.cnblogs.com/zhengyun_ustc/archive/2010/05/18/1738357.html

http://gashero.yeax.com/?p=70