q456123 发表于 2018-8-5 08:09:35

Python多线程编程实例

Python多线程编程
  发布者:lanyulei,转载请注明出处:http://www.fdevops.com/?p=517
  下面多线程模块threading的方法注释,均来自于百度贴吧"学点编程吧"。
  Thread: 表示一个线程的执行对象
  Lock: 锁原语对象(跟Thread模块里的锁对象相同),独占线程资源
  Condition: 条件变量对象能让一个线程停下来,等待其它线程满足了某个“条件”,如状态的改变或值的改变
  Event:通用的条件变量。多个线程可以等待某个事件的发生,在事件发生后,所有的线程都会被激活
  Semaphore为等待锁的线程提供一个类似“等候室”的结构
  BoundedSemaphore与 Semaphore 类似,只是它不允许超过初始值
  Timer与 Thread 相似,只是它要等待一段时间后才开始运行
  activeCount():当前活动的线程对象的数量
  currentThread():返回当前线程对象
  enumerate():返回当前活动线程的列表
  settrace(func):为所有线程设置一个跟踪函数
  setprofile(func):为所有线程设置一个profile 函数
  Thread 对象的函数
  start():开始线程的执行
  run():定义线程的功能的函数(一般会被子类重写)
  join(timeout=None):程序挂起,直到线程结束;如果给了 timeout,则最多阻塞 timeout 秒
  getName():返回线程的名字
  setName(name):设置线程的名字
  isAlive():布尔标志,表示这个线程是否还在运行中
  isDaemon():返回线程的 daemon 标志
  setDaemon(daemonic):把线程的 daemon 标志设为 daemonic(一定要在调用 start()函数前调用)

多线程实例
  多线程与单线程的对比
  代码如下:
  

import threading  
import time
  

  
def sum(n):
  sum = 0
  for i in range(1, n + 1):
  sum += i
  time.sleep(0.001)
  print(sum)
  

  
print("**** Single Thread")
  
time1 = time.time()
  
sum(1000)
  
sum(1000)
  
interval = time.time() - time1
  
print("intervall: ", interval)
  

  
print("**** Multithreading")
  
n =
  
mythread = []
  
time2 = time.time()
  

  
# 将线程对象加入到一个列表中
  
for i in range(len(n)):
  t = threading.Thread(target=sum, args=(n,))
  mythread.append(t)
  

  
# 将列表中的线程对象循环启动
  
for i in range(len(n)):
  mythread.start()
  

  
# 等待线程的结束
  
for i in range(len(n)):
  mythread.join()
  

  
interval2 = time.time() - time2
  
print("interval2: ", interval2)
  

  返回结果如下:
  

**** Single Thread  
500500
  
500500
  
intervall:2.490525245666504
  
**** Multithreading
  
500500
  
500500
  
interval2:1.8753752708435059
  

  多线程锁的操作
  代码如下:
  

import threading  

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

  def run(self):
  global n
  if lock.acquire():# 将线程加锁
  print("Thread: ", n)
  n += 1
  lock.release()   # 释放锁
  

  
n = 0
  
t = []
  
lock = threading.Lock()   # 创建锁对象
  
for i in range(10):
  my = Mythread()
  t.append(my)
  

  
for i in range(10):
  t.start()
  

  
for i in range(10):
  t.join()
  

  意见简单的多线程扫描TCP端口的实例
  代码如下:
  

from socket import *  
import sys
  
import time
  
import threading
  

  
def scan(h, p):
  try:
  tcpCliSock = socket(AF_INET, SOCK_STREAM)
  tcpCliSock.connect((h, p))
  if lock.acquire():
  print(str("{} -> opened".format(p)))
  lock.release()
  except error:
  if lock.acquire():
  print(str("{} -> not open".format(p)))
  lock.release()
  

  finally:
  tcpCliSock.close()
  del tcpCliSock
  

  
posts =
  
HOST = sys.argv
  
lock = threading.Lock()
  
mt = []
  

  
start_time = time.time()
  

  
for p in posts:
  t = threading.Thread(target=scan, args=(HOST, p))
  mt.append(t)
  

  
for i in range(len(posts)):
  mt.start()
  

  
for i in range(len(posts)):
  mt.join()
  
print("end_time: {}".format(time.time() - start_time))
  

  结果如下:
  

F:\script\20180202>python scanner.py 192.168.1.1  
137 -> not open
  
135 -> opened
  
139 -> opened
  
3306 -> opened
  
53 -> not open
  
69 -> not open
  
1433 -> not open
  
80 -> not open
  
21 -> not open
  
1521 -> not open
  
3389 -> not open
  
23 -> not open
  
25 -> not open
  
end_time: 1.108708381652832
页: [1]
查看完整版本: Python多线程编程实例