I have a problem again :)

I try to use this code:

import time
from threading import Thread
from threading import Lock

def main():

    for i in range(3):
        my_thread = MyThread(i)
        my_thread.start()

class MyThread(Thread):
    
    lock = Lock()
    
    def __init__(self, i):
        Thread.__init__(self)
        self.i = i
        
    def run(self):
        while True:
            self.lock.acquire()
            try:
                fh = file("fault.txt","a")
                fh.write("Yo! from thread # %i\n " % self.i)
                fh.flush()
                fh.close()
            finally:
                self.lock.release()

        if __name__ == "__main__":
    main()

and i get this fault mess all the time, when the script is done running.

Traceback (most recent call last):
File "D:\Python26\test.py", line 110, in <module>
main()
File "D:\Python26\test.py", line 19, in main
my_thread = MyThread(i)
NameError: global name 'MyThread' is not defined

why is that?

Edited 6 Years Ago by Godflesh: n/a

Define the class first before you make a reference to it!
although this might not fix your problem

import time
from threading import Thread
from threading import Lock

class MyThread(Thread):
    def __init__(self, i):
        Thread.__init__(self)
        self.i = i
        self.lock = Lock()
        
    def run(self):
        while True:
            self.lock.acquire()
            try:
                fh = file("fault.txt","a")
                fh.write("Yo! from thread # %i\n " % self.i)
                fh.flush()
                fh.close()
            finally:
                self.lock.release()


def main():
   for i in range(3):
        my_thread = MyThread(i)
        my_thread.start()

if __name__ == "__main__":
    main()

Edited 6 Years Ago by jcao219: n/a

Define the class first before you make a reference to it!
although this might not fix your problem

import time
from threading import Thread
from threading import Lock

class MyThread(Thread):
    def __init__(self, i):
        Thread.__init__(self)
        self.i = i
        self.lock = Lock()
        
    def run(self):
        while True:
            self.lock.acquire()
            try:
                fh = file("fault.txt","a")
                fh.write("Yo! from thread # %i\n " % self.i)
                fh.flush()
                fh.close()
            finally:
                self.lock.release()


def main():
   for i in range(3):
        my_thread = MyThread(i)
        my_thread.start()

if __name__ == "__main__":
    main()

ok, it was not solved..
when i use this code i get like thousands of messages written into the fault.txt, strange.

This question has already been answered. Start a new discussion instead.