Question

I was trying to use a thread function in a function. But my terminal says global name 'thread1' is not defined? Is there a possible way to realize it?

My code is like this:

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()  
Was it helpful?

Solution

You miss a global declaration of thread1 in test function:

def test():
    global thread1
    ...

Otherwise, python treats thread1 in test as a local variable, so in main thread1 is not seen as being initialized.

I would suggest though a different approach (that I find more clear and safer):

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()

OTHER TIPS

It's better to use different logic:

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() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top