bh3531 发表于 2014-02-19 10:29

新手学python 多线程 传递参数 问题

#!/usr/bin/python
import threading
import thread
import sys
import time
def func(x):         
    for i in range(x,10 +1):
      print i
      time.sleep(1)
t1 = threading.Timer(0,func(5))
t2 = threading.Timer(0,func(4))
t1.start()
t2.start()

这个多线程原本没有加参数是可以的,现在传递一个参数进去 变成了 单线程,请哥哥们 帮忙修改一下。

timespace 发表于 2014-02-19 11:56

回复 1# bh3531
属于传参错误,看文档class threading.Timer(interval, function, args=[], kwargs={})
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.
一个例子,传参用list#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
import threading

def counter(identity, limit):
    for n in range(limit):
      # stderr无缓存,避免线程间交叉输出
      sys.stderr.write('id = {}, cnt = {}\n'.format(identity, n))
      # print 'id = {}, cnt = {}'.format(identity, n)
      time.sleep(0.5)

def main():
    for i in range(3):
      t = threading.Timer(3, counter, )
      t.start()

if __name__ == '__main__':
    main()Python2.7执行,可能输出id = 0, cnt = 0
id = 2, cnt = 0
id = 1, cnt = 0
id = 2, cnt = 1
id = 0, cnt = 1
id = 1, cnt = 1
id = 2, cnt = 2
id = 0, cnt = 2
id = 1, cnt = 2
id = 1, cnt = 3
id = 2, cnt = 3
id = 2, cnt = 4

bh3531 发表于 2014-02-19 21:23

回复 2# timespace


    哥哥 谢谢你了,你给的例子太好了,一看就明白。
    俺以后学习细心一些多看手册
页: [1]
查看完整版本: 新手学python 多线程 传递参数 问题