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 = [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

转载于:https://blog.51cto.com/11293981/2068355

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值