Home > Backend Development > Python Tutorial > A simple understanding of Python multi-threading and thread locks (code)

A simple understanding of Python multi-threading and thread locks (code)

不言
Release: 2018-09-14 17:16:26
Original
1945 people have browsed it

This article brings you a simple understanding (code) of Python multi-threading and thread locks. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Multi-threading threading module creates threads creates own thread class thread communication thread synchronization mutual exclusion method thread lock @need to understand! ! !

Multi-threading

What is a thread?

Threads are also a multi-tasking programming method that can use computer multi-core resources to complete the concurrent running of programs.

Threads are also called lightweight processes

Characteristics of threads

Threads are the smallest units allocated by computer multi-cores

A process can contain multiple Thread

A thread is also a running process that consumes computer resources. Multiple threads share the resources and space of the process

The creation and deletion of threads consumes far less resources than the process

The execution of multiple threads does not interfere with each other

Threads also have their own unique attributes, such as instruction set ID

threading module creates threads

t=threading.Thread( )

name: thread name, default value if empty, Tread-1, Tread-2, Tread-3

target: thread function

args: element Group, pass parameters to the thread function according to position

kwargs: dictionary, pass parameters to the county function according to key value

Function: Create thread object

Parameters

t.start(): Start the thread and automatically run the thread function

t.join([timeout]): Recycle the process

t.is_alive(): View the thread status

t.name(): View the thread name

t.setName(): Set the thread name

t.daemon attribute: By default, the main thread exits and does not affect the branch thread's continued execution. If set If True, the branch thread exits along with the main thread

t.daemon = True

t.setDaemon(Ture)

Setting method

#!/usr/bin/env python3
from threading import Thread
from time import sleep
import os
# 创建线程函数
def music():
    sleep(2)
    print("分支线程")

t = Thread(target = music)
# t.start()   # ******************************
print("主线程结束---------")

'''没有设置的打印结果
主线程结束---------
分支线程
'''

'''设置为True打印结果
主线程结束---------
'''
Copy after login

threading .currentThread: Get the current thread object

@The code here indicates that the child threads share variables in the same process

#!/usr/bin/env python3
from threading import Thread
from time import sleep
import os

# Create thread function
def music():
global a
print("a=",a)
a = 10000
for i in range(5):
sleep(1)
print("1212")

a = 1
t = Thread(target = music)
t.start()
t.join()
print("a of the main thread =",a) Create your own thread class

Inspection point: use of the class, call the parent class The __init__ method, function *parameter passing and **parameter passing


from threading import Thread
import time

class MyThread(Thread):
    name1 = 'MyThread-1'
    def __init__(self,target,args=(), kwargs={}, name = 'MyThread-1'):
        super().__init__()
        self.name = name
        self.target = target
        self.args = args
        self.kwargs = kwargs
    def run(self):
        self.target(*self.args,**self.kwargs)

def player(song,sec):
    for i in range(2):
        print("播放 %s:%s"%(song,time.ctime()))
        time.sleep(sec)

t =MyThread(target = player, args = ('亮亮',2))

t.start()
t.join()
Copy after login

Thread communication

Communication method: due to multiple threads sharing the memory of the process space, so communication between threads can be completed using global variables

Note: When using global variables between threads, a synchronization mutual exclusion mechanism is often required to ensure the security of communication

Thread synchronization mutual exclusion method

event

e = threading.Event(): Create an event object

e.wait([timeout]): Set the status. If it has been set, then this function will block, and the timeout is Timeout time

e.set: Change e to the setting state

e.clear: Delete the setting state


import threading
from time import sleep

def fun1():
    print("bar拜山头")
    global s
    s = "天王盖地虎"

def fun2():
    sleep(4)
    global s
    print("我把限制解除了")
    e.set()     # 解除限制,释放资源

def fun3():
    e.wait() # 检测限制
    print("说出口令")
    global s
    if s == "天王盖地虎":
        print("宝塔镇河妖,自己人")
    else:
        print("打死他")
    s = "哈哈哈哈哈哈"

# 创建同步互斥对象
e = threading.Event()
# 创建新线程
f1 = threading.Thread(target = fun1)
f3 = threading.Thread(target = fun3)
f2 = threading.Thread(target = fun2)
# 开启线程
f1.start()
f3.start()
f2.start()
#准备回收
f1.join()
f3.join()
f2.join()
Copy after login

Thread lock

lock = threading.Lock(): Create a lock object

lock.acquire(): Lock

lock.release(): Unlock

Also You can use with to lock


1 with lock:
2     ...
3     ...
Copy after login

Need to know! ! !

GIL problem of Python thread (global interpreter):

python---->Support multi-threading---->Synchronization mutual exclusion problem---->Added Lock solution---->Super lock (lock the interpreter)---->The interpreter can only interpret one thread at the same time--->Leading to low efficiency

Consequences:

An interpreter can only interpret and execute one thread at a time, so the Python thread efficiency is low. However, when encountering IO blocking, the thread will actively give up the interpreter, so the Python thread is more suitable for high-latency IO program concurrency

Solution

Try to use processes to complete concurrency (the same as not mentioned)

It is not appropriate to use the C interpreter (use C#, JAVA)

Try to use Concurrent operations are performed through a combination of multiple solutions, and threads are used as high-latency IO

The above is the detailed content of A simple understanding of Python multi-threading and thread locks (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template