编程语言
首页 > 编程语言> > <Notes>Python_Multithreading

<Notes>Python_Multithreading

作者:互联网

<Notes>Python_Multithreading

前言

基本学习目标

学习笔记

theading核心函数大致用法

添加线程:

代码如下:

import threading

def thread_job():
    #查看运行当前程序的线程
    print('This is a thread of %s \n'%threading.current_thread())   # \反斜杠,/正斜杠
    #查看当前线程数
    print(threading.active_count())

def main():
    t1 = threading.Thread(target = thread_job)
    t1.start()
    #print(threading.active_count())  这行代码不能放在这,因为主线程和t1线程不知道谁执行的快,所以有时输出1有时输出2

if __name__ == '__main__':
    main()
    
 #output:
	This is a thread of <Thread(Thread-1, started 1028)> 
	2

join函数:

import threading
import time

def t1_job():
    print('t1 start\n')
    for i in range(10):
        time.sleep(0.1)
    print('t1 finish\n')

def t2_job():
    print('t2 start\n')
    print('t2 finish\n')

def main():
    t1 = threading.Thread(target=t1_job,name='t1')   #这里如果函数加(),程序会先执行一遍函数
    t2 = threading.Thread(target=t2_job,name='t2')
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    print('all done\n')

if __name__ == '__main__':
    main()

Queue功能:

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)   #put是Queue的方法

def multthreading():
    q = Queue()
    threads = []
    data = [[1,2,3],[3,4,5],[2,2,2],[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()
    result = []
    for _ in range(4):
        result.append(q.get())
    print(result)

if __name__ == '__main__':
    multthreading()

GIL机制:

在这里插入图片描述

import threading
from queue import Queue
import copy
import time

def job(l, q):
    res = sum(l)
    q.put(res)

def multithreading(l):
    q = Queue()
    threads = []
    for i in range(4):
        t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i)
        t.start()
        threads.append(t)
    [t.join() for t in threads]
    total = 0
    for _ in range(4):
        total += q.get()
    print(total)

def normal(l):
    total = sum(l)
    print(total)

if __name__ == '__main__':
    l = list(range(1000000))
    s_t = time.time()
    normal(l*4)
    print('normal: ',time.time()-s_t)
    s_t = time.time()
    multithreading(l)
    print('multithreading: ', time.time()-s_t)
    

lock用法:

结果分析:

其他总结

并发编程分为多线程和多进程;Python的多线程是并发而不是并行(多进程是并行);并发和并行从宏观上来讲都是同时处理多路请求的概念; 但并发和并行又有区别,并行是指两个或者多个事件在同一时刻发生;而并发是指两个或多个事件在同一时间间隔内发生。

其他思考

问题1:理论上来说,python程序可以虚拟出任意数量的线程,但如何选择最优线程数呢?

分析:这里多线程并不能加速运算过程,所以无最优线程数一说;这个问题可以留给多进程;

问题2:当代码中有多个线程时,需要多个join,这时候依次加入各个函数的join,这时候主线程是否会卡在第一个join?

分析:是这样的,但是这并不妨碍多个线程运行。

问题3:线程阻塞的概念

分析:阻塞线程的情况下,程序会先等待线程任务执行完,再往下执行其他代码;其实就是join;

学习总结

参考资料

视频资料

1、【莫烦Python】Threading 学会多线程 Python :https://www.bilibili.com/video/BV1jW411Y7Wj.

文档资料

https://www.runoob.com/python3/python3-multithreading.html.

官方资料

https://docs.python.org/3/library/threading.html.

笔记github链接: https://github.com/GRF-Sunomikp31/WorkSpace/blob/main/Python/Python%20Multithreading.md.

标签:__,Python,lock,Notes,t1,threading,线程,print,Multithreading
来源: https://blog.csdn.net/qq_44847636/article/details/114380325