python多线程

使用thread和threading这两个模块.
threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用threading模块实现多线程编程。

使用线程有两种模式:
1)创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
2)直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的class里

函数传递

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import threading
import subprocess

def ping(host):
    p = subprocess.Popen(['ping', '-q', '-c', '5', host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    print threading.currentThread().getName() #获取线程名
    print stdout

def main(num):
    thread_list = []
    for i in num:
        thread_name = 'Thread_%s' % i
        # 创建线程对象, target调用的函数名,name分配线程的名字,args传给函数的值,类型元组
        thread_list.append(threading.Thread(target=ping, name=thread_name, args=('192.168.28.%s' % i,)))

    for thread in thread_list:
        # 启动线程对象
        thread.start()

    for thread in thread_list:
        # 等待子线程退出
        thread.join()

if __name__ == '__main__':
    main(range(1, 255))

继承

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import threading
import subprocess

class myThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        p = subprocess.Popen(['ping', '-q', '-c', '5', self.host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        print threading.currentThread().getName()
        print stdout

if __name__ == '__main__':
    for i in range(1, 255):
        thread = myThread()
        thread.host = '192.168.48.%s' % i
        thread.start()
原文地址:https://www.cnblogs.com/liujitao79/p/4667376.html