python self-study-class22(up)-python thread basic learning

Python thread basic learning

1. Single thread
2. Multi-thread concurrency
3. Passing parameters
4. Main thread and younger thread
5. Multi-thread speed
6. Thread conflict
7. Multi-thread based on class
8. Class thread sequential execution style
9. Class thread chaos Sequential execution style
10. Resolve thread conflicts based on class (car crash problem)
11. Deadlock
12. RLOCK solves single-threaded deadlock
13. The way to create multi-threads
14. Semaphore limits the number of threads
15. Fence lock matching thread number
*

+++++++++++++++++++++++++++++++++++++++++
1. Single thread:
single thread is what The work is done by one person, and the efficiency is low. In the previous study, all the programs were run in a single thread.

import win32api  #引用系统函数
#0代表系统,  "你的账户很危险"代表内容,  "来自支付宝的问候"代表标题,   0-4代表对话类型
win32api.MessageBox(0,"你的账户很危险","来自支付宝的问候",2)

2. Multi-threaded concurrency:
Multi-threading means that more people work at the same time, and the speed of solving one thing is accelerated, but the main thing is that concurrency may cause disorder;

import win32api   #引用系统函数
import _thread    #多线程
def show():
    win32api.MessageBox(0, "你的账户很危险", "来自支付宝的问候", 2)
#顺序执行
#for i in range(5):
#   show()
for i in range(5):
    _thread.start_new_thread(show,())   #()元组,用于传递参数
show()

3. Passing parameters when using multithreading:

import win32api   #引用系统函数
import _thread    #多线程
def show(i):
    win32api.MessageBox(0, "你的账户很危险"+str(i), "来自支付宝的问候", 2)
#顺序执行
#for i in range(5):
#   show()
for i in range(5):
    _thread.start_new_thread(show,(i,))   #()元组,用于传递参数
show(10)

Operation effect:
Insert picture description here
4. Main thread and younger thread:
Stopping the main thread means that all the younger threads no longer work, and stopping the younger thread will not cause the main thread to crash; the way reflected here is to close all the small windows (the younger threads) After that, the program is still running;

import win32api   #引用系统函数
import _thread    #多线程
def show(i):
    win32api.MessageBox(0, "你的账户很危险"+str(i), "来自支付宝的问候", 2)
#顺序执行
#for i in range(5):
#   show()
#主线程,主线程停止后小弟线程不显示
for i in range(5):
    _thread.start_new_thread(show,(i,))   #()元组,用于传递参数
#阻塞,让主线程不死
while True:
    pass

5. The speed of
multi-threading. Due to concurrent execution of multi-threading, generally speaking, the speed will be much faster than single-threaded execution. The test code is as follows:

import _thread
import time
def go():
    for i in range(10):
        print(i,"---------")
        time.sleep(1)
#for i in range(5):   #50秒
#    go()
for i in range(5):
    _thread.start_new_thread(go,()) #10秒
for i in range(12):
    time.sleep(1)
print("game,over")

6. Thread conflict problem:
due to the concurrent operation of multiple threads, each thread running at the same time will inevitably lead to resource preemption and conflict;

import _thread
import time
num=0
def add():
    global num
    for i in range(10000):
        num+=1
    print(num)
'''
for i in range(5):
    add()
'''
#不报错,但是结果不正确
for i in range(5):
    _thread.start_new_thread(add,())
while True:
    pass

7. Realize multithreading based on class:
Use class to encapsulate multithreading, which needs to be inherited

import threading
import time
import win32api
class Mythread(threading.Thread):      #继承threading.Thread
    def run(self):    #run重写
        win32api.MessageBox(0,"你的账户很危险","来自支付宝的问候",2)
for i in range(5):
    t=Mythread()   #初始化
    t.start()    #开启

while True:
    pass

8. Sequential execution style of class threads:
In order to solve the problem of thread concurrency conflicts, you can use join() sequential execution style:

import threading
import time
import win32api
class Mythread(threading.Thread):      #继承threading.Thread
    def run(self):    #run重写
        win32api.MessageBox(0,"你的账户很危险","来自支付宝的问候",2)

for i in range(5):
    t=Mythread()   #初始化
    t.start()    #开启
    t.join()   #主线程等待线程t执行完成,解决线程冲突的一种方法

9. Out-of-order execution style of class threads:

import threading
import time
import win32api
class Mythread(threading.Thread):      #继承threading.Thread
    def run(self):    #run重写
        win32api.MessageBox(0,"你的账户很危险","来自支付宝的问候",2)

mythread=[]  #list
for i in range(5):
    t=Mythread()   #初始化
    t.start()
    mythread.append(t)   #加入线程集合


for mythd in mythread:  #mysthd 是一个线程
    t.join()   #主线程等待线程t完成,不需要阻塞
print("over")

10. Resolve thread conflict based on class:
here is the use of LOCK() to solve the problem of thread conflict, that is, to lock the resource. During the lock, other people can't work, but it may cause deadlock, that is, it is locked all the time. , No one can work

import threading
import time

num=0
mutex=threading.Lock()   #创建一个锁
class Mythread(threading.Thread):
    def run(self):
        global num
        if mutex.acquire(1):   #锁住成功,没有锁住成功则一直等待,1代表参数,独占
            for i in range(100000):   #锁定期间其他人不能干活
                num+=1
            mutex.release()  #释放锁
        print(num)
mythread=[]
for i in range(5):
    t=Mythread()
    t.start()
    mythread.append(t)
for t in mythread:
    t.join()
print("over!")

11. Deadlock: A
deadlock can be visually expressed as a quarrel between boy and girl friends, and no one can apologize first, that is, two threads lock each other's resources and not release them, and then wait for the other party to apologize (release) first, thus forming a deadlock ;

import threading
import time
boymutex=threading.Lock()  #创建一个锁
girlmutex=threading.Lock()

class boy(threading.Thread):
    def run(self):
        if boymutex.acquire(1):   #锁定成功继续执行,锁定不成功,继续等待
            print("boy  say  i  am  sor  up")
            time.sleep(3)
            if girlmutex.acquire(1):#锁定不成功,一直等待
                print("boy  say  i  am  sor  down")
                girlmutex.release()
            boymutex.release()
class girl(threading.Thread):
    def run(self):
        if girlmutex.acquire(1):#锁定成功继续执行,锁定不成功,继续等待
            print("girl  say  i  am  sor  up")
            time.sleep(3)
            #girlmutex.release()  #放在这儿可以解开死锁,女生先释放
            if boymutex.acquire(1):#锁定不成功,一直等待
                print("gril  say  i  am  sor  down")
                boymutex.release()
            girlmutex.release()

#开启俩个线程
boy1=boy()
boy1.start()
girl1=girl()
girl1.start()

12. Use RLOCK to solve single-threaded deadlock:

import threading
import time

num=0
#mutex=threading.Lock()  #LOCK
mutex=threading.RLock()  #RLOCK可以避免单线程死锁
class Mythread(threading.Thread):
    def run(self):
        global num
        if mutex.acquire(1):
            num=num+1
            print(self.name,num)
            if mutex.acquire(1):   #这里形成了死锁
                num+=1000
                mutex.release()
            mutex.release()

for i in range(5):  #开启五个线程
    t=Mythread()
    t.start()

13. Ways to create multithreading:
There are three ways: one is the function method, the other is the inheritance method of the class, and the third is the class method

'''
#第一种风格:函数创建,不考虑冲突与通信
import win32api   #引用系统函数
import _thread    #多线程

def show():
    win32api.MessageBox(0, "你的账户很危险", "来自支付宝的问候", 2)
#顺序执行
#for i in range(5):
#   show()
for i in range(5):
    _thread.start_new_thread(show,())   #()元组,用于传递参数
show()
'''
#第二种风格用类来创建,通过继承实现
import threading
import time
import win32api
class Mythread(threading.Thread):      #继承threading.Thread
    def __init__(self,num):
        threading.Thread.__init__(self)#父类初始化
        self.num=num
    def run(self):    #run重写
        win32api.MessageBox(0,"你的账户很危险"+str(self.num),"来自支付宝的问候",2)

for i in range(5):
    t=Mythread(i)   #初始化
    t.start()    #开启
    t.join()   #主线程等待线程t执行完成,解决线程冲突的一种方法

'''
#第三种风格也是类构建,target=show线程函数,args=()参数
import win32api   #引用系统函数
import threading
def show(i):
    win32api.MessageBox(0, "你的账户很危险"+str(i), "来自支付宝的问候", 2)

threading.Thread(target=show,args=(1,)).start()
threading.Thread(target=show,args=(2,)).start()
threading.Thread(target=show,args=(3,)).start()
'''

14. Semaphore limits the number of threads.
When there is a lot of work that needs to be done, the number of threads cannot be allowed to grow indefinitely. Therefore, the number of threads needs to be limited. The first way is to limit the number of threads through semaphores, that is, limit the maximum number of processes. When the maximum number of threads is reached, latecomers need to wait for the previous thread to finish releasing resources before executing.

import threading
import time
sem=threading.Semaphore(2)#限制线程最大数量为2个

def gothread():
    with sem:  #锁定数量
        for i in range(10):
            print(threading.current_thread().name,i)
            time.sleep(1)

for i in range(5):
    threading.Thread(target=gothread).start()

15. Fence lock the number of matching threads
The second type is to lock the number of matching threads through a fence, that is, in order to use resources reasonably, n threads must be prepared to execute together, and less than n threads will wait together, which is similar to the effect of a fence.

import threading
import time
#为了合理利用资源,必须n个线程一起执行
bar = threading.Barrier(2)  #必须凑一对才能一起执行

def saver():
    print(threading.current_thread().name, "satrt")
    time.sleep(3)
    bar.wait()
    print(threading.current_thread().name, "end")

for i in range(5):
    threading.Thread(target=saver).start()

to sum up:

The knowledge of threads actually took more than a day, not a morning, because it is more important, I feel that the previous crawlers and data retrieval can be efficiently implemented by multi-threading.

Guess you like

Origin blog.csdn.net/weixin_46837674/article/details/113826613