Python多線程編程實例

Python多線程編程

發佈者: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
相關文章
相關標籤/搜索