我的Python自学之路测试员的那点事

python 多线程知识全面解析

2020-08-22  本文已影响0人  望月成三人

非阻塞启动线程

import threading
import time
def one_thread(name,id):
    print("start....")
    print(name)
    print(id)
    time.sleep(5)
    print("end...")

print("start thread")
threading.Thread(target=one_thread, args=(), kwargs={"name": 111, "id": 222}).start()
# args是一个list
# kwargs是一个字典,需要对应函数的key
print("end thread")
start thread
start....
111
222
end thread
end...

多线程并发处理

import threading
import time


class myThread(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):
        print_time(self.threadID, self.name)

num = 0
def print_time(threadID, name):
    global num
    # 每一个线程循环10次,最终总循环次数为30次
    for i in range(10):
        print("start run")
        time.sleep(2)
        print(i)
        num += 1
    print("thread_id=%s:name=%s" % (threadID, name))


if __name__ == '__main__':
    threads = []
    # 新增三个线程
    for i in range(3):
        name = "Thread-%d" % i
        t = myThread(i, name)
        t.start()
        threads.append(t)
    for t in threads:
        t.join()
    print("所有线程执行完毕")
    print("总循环次数为:%s" % num)
start run
start run
start run
0
0
...
thread_id=1:name=Thread-1
所有线程执行完毕
总循环次数为:30

多线程加锁

# -*- coding: utf-8 -*-
import time
import threading
# 创建锁对象
lock = threading.Lock()
num = 0

def run(n):
    global num
    for i in range(10):
        # 加锁  为了确保下面代码只能由一个线程从头到尾的执行
        # 会阻止多线程的并发执行,所以效率会大大降低
        """
        lock.acquire()
        try:
            num = num - n
            num = num + n
        finally:
            # 解锁
            lock.release()
        """
        with lock:
            time.sleep(2)
            print("start")
            num = num + 1
            print("==============")


if __name__ == '__main__':
    t1 = threading.Thread(target=run,args=(6,))
    t2 = threading.Thread(target=run,args=(9,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print("num = %s"%(num))
start
==============
...
num = 20

多线程与队列

import threading
import time
import queue

q = queue.Queue(10)

threadLock = threading.Lock()


class myThread(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.exitFlag = 0

    def run(self):
        while not self.exitFlag:
            threadLock.acquire()
            if not q.empty():
                id = q.get()
                print_time(self.name, id)
                threadLock.release()
            else:
                threadLock.release()


def print_time(threadName, id):
    print ("%s:%s:%s"%(threadName,time.ctime(time.time()),id))
    # pass


# 创建3个线程
threads = []
for i in range(3):
    name = "Thread-%d" % i
    t = myThread(i, name)
    t.start()
    threads.append(t)
print(threads)

# 新增队列数据
for i in range(10000):
    q_name = "Queue:%d" % i
    q.put(q_name)

# 等待队列清空
while not q.empty():
    pass

# 也可以join方法,与上同效
# q.join()

# 通知线程,处理完之后关闭
for t in threads:
    t.exitFlag = 1

# 等待所有线程结束之后才退出
for t in threads:
    t.join()

print("Exiting Main Thread")
[<myThread(Thread-0, started 6568)>, <myThread(Thread-1, started 7724)>, <myThread(Thread-2, started 7796)>]
Thread-1:Sat Aug 22 11:36:29 2020:Queue:0
Thread-1:Sat Aug 22 11:36:29 2020:Queue:1
...
Thread-1:Sat Aug 22 11:36:30 2020:Queue:9998
Thread-1:Sat Aug 22 11:36:30 2020:Queue:9999
Exiting Main Thread

ThreadPoolExecutor线程池的使用

from concurrent.futures.thread import ThreadPoolExecutor
import time
num = 0
def print_time(data):
    global num
    num += 1
    time.sleep(2)
    print("start_%s" % data)
    print("============")
data = []
for i in range(50):
    data.append(i)
with ThreadPoolExecutor(10) as pool:
    result = pool.map(print_time, data)
# 等待所有线程执行完毕
for i in result:
    pass
print("循环次数=%s" % num)

============
start_46
start_49
============
============
循环次数=50
rom concurrent.futures.thread import ThreadPoolExecutor
from concurrent.futures import as_completed

import time
def print_time(data):
    time.sleep(2)
    print("start_%s" % data)
    print("============")
data = []
for i in range(50):
    data.append(i)
with ThreadPoolExecutor(10) as executor:
    future_list = []
    for i in range(10):
        # future = executor.submit(print_time,data)
        future = executor.submit(print_time, {"name": 111, "id": 222})
        future_list.append(future)
    for res in as_completed(future_list):  # 这个futrure_list是你future对象的列表
        print(res.result())

参考

上一篇下一篇

猜你喜欢

热点阅读