Python Forum

Full Version: more thread question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I downloaded this code from SO. I tried it and it works in terminal. But I am puzzled that at the very end it has two statements a.join() and b.join(). I don't why konw they are there bucause when I comment them out, the code works just fine. Thanks.

import threading
import time
c = threading.Condition()
flag = 0      #shared between Thread_A and Thread_B
val = 20

class Thread_A(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run(self):
        global flag
        global val     #made global here
        while True:
            c.acquire()
            if flag == 0:
                print ("A: val=" + str(val))
                time.sleep(0.1)
                flag = 1
                val = 30
                c.notify_all()
            else:
                c.wait()
            c.release()


class Thread_B(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run(self):
        global flag
        global val    #made global here
        while True:
            c.acquire()
            if flag == 1:
                print ("B: val=" + str(val))
                time.sleep(0.5)
                flag = 0
                val = 20
                c.notify_all()
            else:
                c.wait()
            c.release()


a = Thread_A("myThread_name_A")
b = Thread_B("myThread_name_B")

b.start()
a.start()

a.join()
b.join()
.join() will wait until that thread is finished.  If you don't call it, there won't be any errors or anything, but the main program might finish before the threads are done, so if there was some processing or output they were doing, you might not see it, because they maybe will be killed when python exits before they complete.

That's one of the tricky things about working with threads... sometimes it'll seem like it's working fine, and sometimes it won't, even though you've made no changes to your code.
Haha Thank you for the reply. It is kinda weired that there is thread.start() but no thread.stop()or is there?
I was lookimg up on that earlier. I guess thread.join() does a better job? The name "join" is kinda missleading tho. silly me I thouhg at first it means joing two thread into one. :p
There's no thread.stop(), because once a thread starts, it's sort of up to that thread to decide when it's done running, and other things shouldn't be able to tell it when to stop.  Thread.join() sort of does mean two threads are joining into one... when you call it, there are two threads, and it waits until the thread is done running before returning, so there's only one left after calling .join().