[关闭]
@Dukebf 2017-07-11T16:14:25.000000Z 字数 1876 阅读 1125

python多线程

python 多线程


前人轮子
Python模块学习:threading 多线程控制和处理

目录

threading.Thread

Thread是threading模块中重要的类.创建线程可以有两种方法:

继承的例子

使用继承来使用多线程,可以对线程进行更多的自定义.如线程锁,线程等待,定义线程名字等等.
线程一般可以和队列Queue进行搭配.
输出打印IP

  1. #!/usr/bin/python
  2. #-*-coding:utf-8-*-
  3. import threading
  4. from queue import Queue
  5. class Thread_ip(threading.Thread):
  6. def __init__(self,thread_name,queue):
  7. super(Thread_ip,self).__init__(name=thread_name)
  8. # 使用super显示调用父类
  9. # 也可以使用下面的方法,显示调用
  10. # threading.Thread().__init__(self,name=thread_name)
  11. # thread_stop: (可选)指定线程是否停止
  12. self.name = thread_name
  13. self.thread_stop = False
  14. self.__queue = queue
  15. def run(self):
  16. """ (必须重写)重写父类run方法,线程启动后执行该方法
  17. """
  18. while not self.__queue.empty():
  19. print(self.__queue.get(),'name:{}'.format(self.name))
  20. def stop(self):
  21. """ (可选)重写父类stop方法,调用时线程停止
  22. """
  23. self.thread_stop = True
  24. if __name__ == '__main__':
  25. Q = Queue()
  26. for i in range(255):
  27. Q.put('180.149.132.%s' % i)
  28. max_thread = 5 # 定义最大线程数量
  29. threads = []
  30. while not Q.empty():
  31. # 队列还没有空
  32. if len(threads) < max_thread and not Q.empty():
  33. # 还可以增加线程,启用新线程
  34. thread = Thread_ip(queue=Q,thread_name='thread-'+str(max_thread-len(threads)))
  35. thread.start() # 启动线程
  36. threads.append(thread)
  37. for thread in threads:
  38. if not thread.is_alive():
  39. # 停止已经不活动的线程
  40. # 并从当前的线程列表中移出
  41. thread.stop()
  42. threads.remove(thread)
  43. if Q.empty():
  44. # 如果队列已经空了,则将当前正在执行的线程退出
  45. for thread in threads:
  46. thread.join()
  47. print('continue')
  48. print('end')

线程在执行的各个过程,可以自行打印看看效果.
除了用while循环控制线程,还可以简单的用for循环控制线程数.
将上面的while循环修改:

  1. # 设定最大线程数
  2. max_thread = 5
  3. threads = []
  4. for i in range(max_thread):
  5. # 初始化线程
  6. thread = Thread_ip(queue=Q,thread_name='thread-'+str(i))
  7. threads.append(thread)
  8. # 启动线程,并将让主线程阻塞
  9. for thread in threads:
  10. thread.start()
  11. for thread in threads:
  12. thread.join()
  13. print('end')

使用对象的例子

对象的使用就相对比较简单

  1. import threading
  2. import time
  3. def print_ip(ip):
  4. time.sleep(1)
  5. print('ip: {}'.format(ip))
  6. for i in range(5):
  7. ip = '192.168.0.%s' % i
  8. t = threading.Thread(target=print_ip,args=(ip,))
  9. t.start()
  10. print('end')

上面的例子中,只是简单的创建了线程
此外,也还可以用队列Queue来传输数据
join()方法可以可以阻塞主进程.达到让所有线程都结束了,主进程才退出的效果.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注