pythonマルチスレッド使用およびCtrl+C終了
5069 ワード
マルチスレッドインスタンスおよびCtrl+Cを使用してマルチスレッドを終了
#!/usr/bin/env python
#coding: utf-8
import time, threading
import random
import socket
import signal
HOST = '192.168.1.110'
UDPPORT = 8888
address = (HOST, UDPPORT)
thread_num = 5 #open thread num
sendto_time = 1 #sendto sleep time
is_exit = True
start_time = 0
thread_count = range(0,thread_num)
def SendToData(sock,address,str):
sock.sendto(str,address)
def clientThread(arg,val):
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
count = 0
while is_exit:
count += 1
global thread_count
thread_count[arg] = count
str = 'index:%d count:%d' % (arg, count)
SendToData(sock, address, str)
print '[%d:%d]Sendto ...
' % (arg, count)
time.sleep(sendto_time)
sock.close()
ncli = range(0,thread_num)
threads = []
def press_test():
try:
for i in ncli:
t = threading.Thread(target=clientThread, args=(i,0))
t.setDaemon(True)
threads.append(t)
for i in ncli:
threads[i].start()
#for i in ncli:
# threads[i].join()
except KeyboardInterrupt:
print 'end'
def signal_handler(signum, frame):
tatol_count = 0
time_count = int(time.time() - start_time)
global is_exit
is_exit = False
time.sleep(1)
print '
***********Test Result**********'
for i,val in enumerate(thread_count):
tatol_count += val
print 'index:%d count:%d' % (i,val)
print 'Press test time:%ds' % (time_count)
print 'Press test tatol count:%d' % (tatol_count)
if time_count > 0:
print 'Press test average second num:%d' % (tatol_count/time_count)
print '*************************************
'
if __name__ == '__main__':
global start_time
start_time = time.time()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
press_test()
while True:
alive = False
for i in ncli:
alive = alive or threads[i].isAlive()
time.sleep(0.01)
if not alive:
break