1

Python (2.7) で新しいスレッドが開始されるたびに任意のメソッドを実行する方法はありますか? 私の目標は、setproctitleを使用して、生成された各スレッドに適切なタイトルを設定することです。

4

2 に答える 2

5

スレッドを制御できる限り、threading.Threadから継承し、Threadの代わりにこのクラスを使用してください。

import threading

class MyThread(threading.Thread):
    def __init__(self, callable, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        self._call_on_start = callable
    def start(self):
        self._call_on_start()
        super(MyThread, self).start()

粗いスケッチと同じように。

編集 コメントから、既存のアプリケーションに新しい動作を「注入」する必要が生じました。それ自体が他のライブラリをインポートするスクリプトがあると仮定しましょう。これらのライブラリはthreadingモジュールを使用します:

他のモジュールをインポートする前に、まずこれを実行します。

import threading 
import time

class MyThread(threading.Thread):
    _call_on_start = None

    def __init__(self, callable_ = None, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        if callable_ is not None:
            self._call_on_start = callable_

    def start(self):
        if self._call_on_start is not None:
            self._call_on_start
        super(MyThread, self).start()

def set_thread_title():
    print "Set thread title"

MyThread._call_on_start = set_thread_title()        
threading.Thread = MyThread

def calculate_something():
    time.sleep(5)
    print sum(range(1000))

t = threading.Thread(target = calculate_something)
t.start()
time.sleep(2)
t.join()

後続のインポートはでのみルックアップを実行するため、sys.modulesこれを使用する他のすべてのライブラリは、新しいクラスを使用する必要があります。私はこれをハックと見なしており、奇妙な副作用があるかもしれません。しかし、少なくとも試してみる価値はあります。

注意:threading.ThreadPythonで同時実行を実装する方法はこれだけではありません。他にも、multiprocessingなどのオプションがあります。これらはここでは影響を受けません。

編集2 あなたが引用したライブラリを見てみましたが、それはすべてプロセスに関するものであり、スレッドに関するものではありません。だから、とを実行するだけ:%s/threading/multiprocessing/g:%s/Thread/Process/g、物事はうまくいくはずです。

于 2013-01-14T14:58:48.863 に答える