python多线程不能在我的代码中工作?

时间:2014-12-12 11:16:35

标签: python

from threading import Thread

def multithread():
    t1= Thread(target = producer)
    t1.run()

    t2 = Thread(target = consumer)
    t2.run()

def producer():
    print "current thread id is {0}".format(Thread.name)

def consumer():
    print "current thread id is {0}".format(Thread.name)

运行结果显示我们在同一个线程?为什么?我的代码有什么不对吗?

current thread id is <property object at 0x7fc7839acf18>
current thread id is <property object at 0x7fc7839acf18>

2 个答案:

答案 0 :(得分:1)

如果你在文件末尾添加它

print Thread.name

您将看到您从类中询问从模块线程导入的名称,而不是从您创建的对象中获取名称。

from threading import Thread

def multithread():
    t1= Thread(target = producer)
    print t1.name
    t1.run()

    t2 = Thread(target = consumer)
    print t2.name
    t2.run()

def producer():
    print "current thread id is {0}".format(Thread.name)

def consumer():
    print "current thread id is {0}".format(Thread.name)

Thread-1
current thread id is <property object at 0x7f10752a45d0>
Thread-2
current thread id is <property object at 0x7f10752a45d0>

现在我们得到了你的线程的真实姓名。

修改 我知道了。你调用run()方法只在主线程中运行目标函数。要在新线程中启动函数,必须调用方法start()。

from threading import Thread, current_thread

def multithread():
    t1= Thread(target = producer)
    t2 = Thread(target = consumer)

    for t in [t1, t2]:
        t.start()

    for t in [t1, t2]:
        t.join()

def producer():
    print "current thread id is {0}".format(current_thread())

def consumer():
    print "current thread id is {0}".format(current_thread())


multithread()

输出将是这样的

current thread id is <Thread(Thread-1, started 139800907732736)>
current thread id is <Thread(Thread-2, started 139800899340032)>

答案 1 :(得分:0)

from threading import current_thread
...
def producer():
    print "current thread id is {0}".format(current_thread())

...etc

参考:Python : Running function in thread does not modify current_thread()