如何在函数内部使用线程实例函数?

时间:2014-02-17 12:43:33

标签: python python-multithreading

我试图在函数中使用线程函数。但我的终端说全局名称'thread1'没有定义?有没有可能实现它的方法?

我的代码是这样的:

import time
import threading

count = 0

class Screen(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.thread_stop = False

    def run(self):
        while not self.thread_stop:
            main()
    def stop(self):
        self.thread_stop = True


def test():
    thread1 = Screen() 
    thread1.start()

def main():
    global thread1,count
    while True:
        time.sleep(1)
        count += 1
        if count >=3:
            thread1.stop()
            print "Stop!"
            break

test()  

2 个答案:

答案 0 :(得分:0)

您错过了thread1函数中test的全局声明:

def test():
    global thread1
    ...

否则,python会将thread1中的test视为局部变量,因此在主thread1中不会将其视为已初始化。

我建议采用不同的方法(我发现更清晰,更安全):

import time
import threading

count = 0

class Screen(threading.Thread):
    def __init__(self, count):
        threading.Thread.__init__(self)
        self.count = count

    def do_something(self):
        while True:
            time.sleep(1)
            self.count += 1
            if self.count >=3:
                print "Stop!"
                break

    def run(self):
        self.do_something()

def test():
    thread1 = Screen(count)
    thread1.start()

test()

答案 1 :(得分:0)

最好使用不同的逻辑:

from threading import Thread, Event
import time

evt_stop = Event() 

def activity(): 
    count = 0 
    while not evt_stop.is_set(): 
        time.sleep(1) 
        count += 1 
        if count >=3: 
            evt_stop.set() 
            print "Stop!" 
        break 


thread = Thread(target=activity) 
thread.start() 
thread.join()