鱼C论坛

 找回密码
 立即注册
查看: 2157|回复: 3

[已解决]关于threads多次开始的疑问

[复制链接]
发表于 2016-10-18 01:53:44 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
比如有下面一段代码:
  1. # coding = utf-8
  2. import time
  3. import threading
  4. import random

  5. def p(i):
  6.     print (i)
  7.     time.sleep(random.randint(1,3))
  8.     print(i)

  9. threads2 = []

  10. for i in range(0, 2):
  11.     threads2.append(threading.Thread(target=p, args=(i,)))
  12. while 1:
  13.     time.sleep(10)
  14.     for t in threads2:
  15.         t.start()
复制代码


运行后会有如下报错信息。
threading.PNG
这个应该是threads只能运行一次吧。但是我的程序就是要定时或者每过多少时间去启动一次这些线程(可以保证上一次运行的已经全部结束)。那么怎么办呢?
最佳答案
2016-10-18 16:44:46
如果用的python3可以试试这样。
  1. from concurrent.futures import ThreadPoolExecutor

  2. import time

  3. def a(v, i):
  4.     print(v)
  5.     time.sleep(i)


  6. with ThreadPoolExecutor(max_workers=2) as t:
  7.     t.submit(a, '5', 10)
  8.     t.submit(a, '6', 5)
  9.     t.submit(a, '7', 7)
  10.     t.submit(a, '8', 9)  
复制代码


加个while就行了。

2没试过。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-10-18 11:55:40 | 显示全部楼层
while 循环写到线程里
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-10-18 16:44:46 | 显示全部楼层    本楼为最佳答案   
如果用的python3可以试试这样。
  1. from concurrent.futures import ThreadPoolExecutor

  2. import time

  3. def a(v, i):
  4.     print(v)
  5.     time.sleep(i)


  6. with ThreadPoolExecutor(max_workers=2) as t:
  7.     t.submit(a, '5', 10)
  8.     t.submit(a, '6', 5)
  9.     t.submit(a, '7', 7)
  10.     t.submit(a, '8', 9)  
复制代码


加个while就行了。

2没试过。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-10-18 18:03:26 | 显示全部楼层
  1. while 1:
  2.     time.sleep(10)
  3.     for t in threads2:
  4.         print t.__dict__
  5.         t.start()
复制代码

尝试打印t
会发现while 第一次进和第二次进入 threads2元素的值是不同的
第一次:
{'_Thread__ident': None, '_Thread__block': <Condition(<thread.lock object at 0x7f01140361f0>, 0)>, '_Thread__name': 'Thread-1', '_Thread__daemonic': False, '_Thread__started': <threading._Event object at 0x7f0113f29dd0>, '_Thread__stderr': <open file '<stderr>', mode 'w' at 0x7f01140851e0>, '_Thread__target': <function p at 0x7f0112072668>, '_Thread__kwargs': {}, '_Verbose__verbose': False, '_Thread__args': (0,), '_Thread__stopped': False, '_Thread__initialized': True}
第二次:
{'_Thread__ident': 139642559399680, '_Thread__block': <Condition(<thread.lock object at 0x7f01140361f0>, 0)>, '_Thread__name': 'Thread-1', '_Thread__daemonic': False, '_Thread__started': <threading._Event object at 0x7f0113f29dd0>, '_Thread__stderr': <open file '<stderr>', mode 'w' at 0x7f01140851e0>, '_Verbose__verbose': False, '_Thread__stopped': True, '_Thread__initialized': True}
所以把生成threads2变量的循环封装到一个函数里就好了 for t in get_threads()类似
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 14:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表