第 13 章 线程

前言

本文对线程进行了一个简要介绍。


13.1 显示线程性质

import threading
import time
from queue import Queue
print("已激活线程数量为:",threading.active_count())
print("已激活线程名称为:",threading.enumerate())
print("正在运行线程为:",threading.current_thread())

输出
已激活线程数量为: 1
已激活线程名称为: [<_MainThread(MainThread, started 1980)>]
正在运行线程为: <_MainThread(MainThread, started 1980)>

13.2 多线程运行

import threading
import time
from queue import Queue
def thread_job_1():
    for j in range(10):
        time.sleep(0.1)
        print("T1等待时间为%d"%j)
    print("T1 finish")
def thread_job_2():
    for i in range(10):
        time.sleep(0.1)
        print("T2等待时间为%d"%i)
    print("T2 finish")
def main():
    Thread_1 = threading.Thread(target=thread_job_1)  # 添加线程
    Thread_1.start()  # 开启线程
    Thread_1.join()   # 将线程添加到主函数中
    Thread_2 = threading.Thread(target=thread_job_2)  # 添加线程
    Thread_2.start()  # 开启线程
    print("all done")
main()

输出
T1等待时间为0
T1等待时间为1
T1等待时间为2
T1等待时间为3
T1等待时间为4
T1等待时间为5
T1等待时间为6
T1等待时间为7
T1等待时间为8
T1等待时间为9
T1 finish
all done
T2等待时间为0
T2等待时间为1
T2等待时间为2
T2等待时间为3
T2等待时间为4
T2等待时间为5
T2等待时间为6
T2等待时间为7
T2等待时间为8
T2等待时间为9
T2 finish

13.3 多线程运行返回函数值

import threading
import time
from queue import Queue
def job(l,q):
    for i in range (len(l)):
        l[i]=l[i]**2
    q.put(l)

def multithreading():
    q = Queue()
    threads =[]
    data = [[1, 2, 3],[3, 4, 5],[4, 4, 4],[5, 5, 5]]
    for i in range(4):
        t = threading.Thread(target = job, args = (data[i], q))
        t.start()
        threads.append(t)
    for thread in threads:
        thread.join()
    results = []
    for _ in range(4):
        results.append(q.get())
    print(results)
multithreading()

输出
[[1, 4, 9], [9, 16, 25], [16, 16, 16], [25, 25, 25]]

13.4 多线程锁

import threading
import time
from queue import Queue
def job1():
    global A, lock
    lock.acquire()
    for i in range(10):
        A += 1
        print('job1', A)
    lock.release()
def job2():
    global A, lock
    lock.acquire()
    for i in range(10):
        A += 10
        print('job2',A)
    lock.release()
if __name__ == '__main__':
    lock = threading.Lock()
    A = 0
    T1 = threading.Thread(target=job1)
    T2 = threading.Thread(target=job2)
    T1.start()
    T2.start()
    T1.join()
    T2.join()

输出
job1 1
job1 2
job1 3
job1 4
job1 5
job1 6
job1 7
job1 8
job1 9
job1 10
job2 20
job2 30
job2 40
job2 50
job2 60
job2 70
job2 80
job2 90
job2 100
job2 110


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值