发布者:lanyulei,转载请注明出处:http://www.fdevops.com/?p=517python
下面多线程模块threading的方法注释,均来自于百度贴吧"学点编程吧"。编程
Thread: 表示一个线程的执行对象多线程
Lock: 锁原语对象(跟Thread模块里的锁对象相同),独占线程资源app
Condition: 条件变量对象能让一个线程停下来,等待其它线程知足了某个“条件”,如状态的改变或值的改变socket
Event:通用的条件变量。多个线程能够等待某个事件的发生,在事件发生后,全部的线程都会被激活tcp
Semaphore为等待锁的线程提供一个相似“等候室”的结构ide
BoundedSemaphore与 Semaphore 相似,只是它不容许超过初始值函数
Timer与 Thread 类似,只是它要等待一段时间后才开始运行post
activeCount():当前活动的线程对象的数量ui
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 = [1000, 1000] mythread = [] time2 = time.time() # 将线程对象加入到一个列表中 for i in range(len(n)): t = threading.Thread(target=sum, args=(n[i],)) mythread.append(t) # 将列表中的线程对象循环启动 for i in range(len(n)): mythread[i].start() # 等待线程的结束 for i in range(len(n)): mythread[i].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[i].start() for i in range(10): t[i].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 = [21, 23, 25, 53, 69, 80, 135, 137, 139, 1521, 1433, 3306, 3389] HOST = sys.argv[1] 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[i].start() for i in range(len(posts)): mt[i].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