python 多线程
多线程运行,每个线程以追加的方式写入文件,不读取文件,是否需要加锁处理,此处没加锁
下面展示一些 内联代码片
。
-- coding: utf-8 --
import threading
import subprocess
import time
from queue import Queue
ipqueue = Queue()
for item in range(255,100,-1):
IP_QUEUE.put(“192.”+ str(item) + “.1.16”)
def ping2ip(file):
while not ipqueue.empty():
ip = ipqueue.get()
res = subprocess.call(‘ping -n 2 -w 3 %s’ %ip, stdout=subprocess.PIPE)
if res==0:
print(“IP: %s ; TRUE\n” %ip)
else:
file.append(ip)
ipqueue.task_done()
if name == ‘main’:
threads = []
start_time = time.time()
fp = open(“ping.txt”,‘w+’)
IPArray = []
for item in range(0,30):
thread = threading.Thread(target=ping2ip,args=(IPArray,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
fp.close()
print(IPArray)
print('end\n')
print('run time: %s' %(time.time() - start_time))