线程模块。不确定我是否创建了多个线程

时间:2014-11-29 19:44:19

标签: python python-multithreading

我正在尝试学习“线程”模块。但是,我不确定我是否能够创建多个线程。

import threading
import time
def somefunction():
    for loop in range (10):
        print "thread sleeps for 20 seconds"
        time.sleep(20)
        print "thread %d woke up"

counter = 0
while counter < 10:
     threader = threading.Thread(target=somefunction())
     counter = counter +1

当我运行以下命令时,它只返回一个NLWP。

ps axo pid,ppid,rss,vsz,nlwp,cmd | grep -i python

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您必须使用参数target中的引用到somefunction,而不是调用该函数。

import threading
import time
def somefunction():
    for loop in range (10):
        print "thread sleeps for 20 seconds"
        time.sleep(20)
        print "thread %d woke up"

for counter in range(10):
     threader = threading.Thread(target=somefunction)