免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 8288 | 回复: 2
打印 上一主题 下一主题

新手学python 多线程 传递参数 问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-02-19 10:29 |只看该作者 |倒序浏览
#!/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()

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

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
2 [报告]
发表于 2014-02-19 11:56 |只看该作者
回复 1# bh3531
属于传参错误,看文档
  1. class threading.Timer(interval, function, args=[], kwargs={})
  2. Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.
复制代码
一个例子,传参用list
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import time
  5. import threading

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

  12. def main():
  13.     for i in range(3):
  14.         t = threading.Timer(3, counter, [i, i + 3])
  15.         t.start()

  16. if __name__ == '__main__':
  17.     main()
复制代码
Python2.7执行,可能输出
  1. id = 0, cnt = 0
  2. id = 2, cnt = 0
  3. id = 1, cnt = 0
  4. id = 2, cnt = 1
  5. id = 0, cnt = 1
  6. id = 1, cnt = 1
  7. id = 2, cnt = 2
  8. id = 0, cnt = 2
  9. id = 1, cnt = 2
  10. id = 1, cnt = 3
  11. id = 2, cnt = 3
  12. id = 2, cnt = 4
复制代码

论坛徽章:
0
3 [报告]
发表于 2014-02-19 21:23 |只看该作者
回复 2# timespace


    哥哥 谢谢你了,你给的例子太好了,一看就明白。
    俺以后学习细心一些多看手册
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP