Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a thread lock in Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to achieve a thread lock in Python, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Each thread is independent of each other and does not have any relationship with each other, but the resources in the same process are shared by threads. If the resources are not allocated reasonably, the data will be destroyed and the results of thread running can not be expected. This phenomenon is called "thread unsafe".

Thread synchronization can ensure that multiple threads can safely access competitive resources, and the simplest synchronization mechanism is to introduce mutex locks. Mutexes introduce a state for resources: locked / non-locked. When a thread wants to change shared data, it is locked first, when the state of the resource is "locked" and cannot be changed by other threads; until the thread releases the resource and changes the state of the resource to "unlocked", other threads can lock the resource again. The mutex ensures that only one thread writes at a time, thus ensuring the correctness of data in the case of multiple threads.

The Lock class is defined in the threading module, which can easily handle locking:

# create a lock

Mutex = threading.Lock ()

# Lock

Mutex.acquire ([timeout]) # timeout is the timeout

# release

Mutex.release ()

Where the locking method acquire can have an optional parameter timeout for timeout. If timeout is set, the lock can be determined by the return value after the timeout, so that some other processing can be done.

# coding:utf-8

Import threading

Start_task = 0

Task_num = 10000

Mu = threading.Lock () # get a new lock object through the factory method

Class MyThread (threading.Thread): # # Class MyThread inherits threading.Thread

Def run (self): # # entry function for thread startup. Subclasses need to be overridden

Global start_task

Global mu

Global start_task

While start_task < task_num: # # if there is no task, continue

If mu.acquire (): # # Lock

If start_task < task_num:

Print start_task

Start_task = start_task + 1

Mu.release () # # release the lock

Def test ():

Thread_all = []

For i in range (10): # # for loop creates 6 threads

T = MyThread () # # create thread

Thread_all.append (t)

T.start () # # start thread

For i in range (10):

Thread_ all [I] .join () # # wait for the thread to finish

If _ _ name__== "_ _ main__":

Test ()

In the threading module, define two types of trivia: threading.Lock and threading.RLock. There is a slight difference between them, which is illustrated by comparing the following two pieces of code:

Import threading

Lock = threading.Lock () # Lock object

Lock.acquire ()

Lock.acquire () # produces deadlock.

Lock.release ()

Lock.release ()

Import threading

RLock = threading.RLock () # RLock object

RLock.acquire ()

RLock.acquire () # in the same thread, the program will not block.

RLock.release ()

RLock.release ()

# coding:utf-8

Import threading

Lock = threading.RLock ()

Ret = lock.acquire (1)

Print (ret)

Ret = lock.acquire (3)

Print (ret)

Ret = lock.acquire (True)

Print (ret)

Ret = lock.acquire (False)

Print (ret)

Lock.release ()

Lock.release ()

Lock.release ()

Lock.release () the above is how to implement a thread lock in Python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report