关于python多线程join()

发布于 2022-08-29 21:58:35 字数 1083 浏览 21 评论 0

import threading
import time

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

    def run(self):
        global x
        con.acquire()

        if x>0:
            con.wait()
        else:
            for i in xrange(0,5,1):
                x+=1
                print u'producing...'+str(x)
            con.notify()
        print x
        con.release()

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

    def run(self):
        global x
        con.acquire()

        if x<0:
            con.wait()
        else:
            for i in xrange(0,5,1):
                x-=1
                print u'consume...'+str(x)
            con.notify()
        print x
        con.release()

con = threading.Condition()
x = 0
print u'start consumer'
c = Consumer('consumer')
print u'start producer'
p = Producer('producer')

p.start()
c.start()
p.join()
c.join()

print x

最后的join()函数的有无对程序结果并无显示作用?请问join()在这里意义何在?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

万人眼中万个我 2022-09-05 21:58:36

不join 主线程结束了你的子线程怎么办

倾听心声的旋律 2022-09-05 21:58:36

Other threads can call a thread’s join() method. This blocks the calling thread until the thread whose join() method is called is terminated.
Thread Objects
threading.Thread.join
阻塞当前调用 thread.join()的进程或者线程,直到join的线程( the thread whose join() method is called )结束,才继续执行当前进程或者线程(the calling thread )~

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文