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?

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

Hello and thanks, i saw the fault now it works rather good.

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.

You have while True: in the run function.
of course it does that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.