【问题标题】:python - multithreading -- join() methodpython - 多线程 - join() 方法
【发布时间】:2012-09-27 13:35:33
【问题描述】:
import threading, time

class test(threading.Thread):                 

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

    def run(self):
        c = 0
        while True:
            time.sleep(self.delay)            
            print 'This is thread %s on line %s' %(self.name,c)
            c = c + 1 
            if c == 15:
                print 'End of thread %s' % self.name
                break

one = test('one', 1).start()
two = test('two', 3).start()

one.join()
two.join()

print 'End of main'

问题:无法让 join() 方法正常工作,出现以下错误:

Traceback (most recent call last)line 29, in <module> join() NameError: name 'join' is not defined

如果我删除:

one.join
two.join

代码运行良好。

我想打印最后一行,

print 'End of main'

两个线程结束后。我似乎无法理解为什么 join() 不是两个实例的属性?

【问题讨论】:

  • 对不起——这里是新手。我试过了
  • 我的意思是在你的帖子中。我认为您的程序看起来不同,否则您不会走那么远。
  • 是的,我知道你的意思。我做错了。我知道这是4个空格缩进。就像例如在其余代码块的实际代码下方,我已经设法让它正确。不知道为什么会这样。
  • @atabrizi 的编辑看起来也不好。我会试试的。
  • 不够快,但仅此而已。

标签: python multithreading join exit


【解决方案1】:
one = test('one', 1).start()
two = test('two', 3).start()

您的问题是start() 没有执行return selfonetwo 不是线程。它们是 Nonestart() 的实际返回值。

这行得通:

one = test('one', 1)
one.start()
two = test('two', 3)
two.start()

【讨论】:

  • 你们都打败了我。所以说 23 秒!
  • 太棒了!!没有意识到这更多地与 RETURN 有关,我更专注于代码缩短。总之谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多