current position:Home>Python thread 03 thread synchronization

Python thread 03 thread synchronization

2022-02-01 06:46:14 Lei Xuewei

「 This is my participation 11 The fourth of the yuegengwen challenge 20 God , Check out the activity details :2021 One last more challenge

ceremonial Python Column No 42 piece , Classmate, stop , Don't miss this from 0 The beginning of the article !

The previous two articles introduced the concept of threading and the code demonstration of multithreaded programs , But in multithreaded programs , They print independently of each other, but the time is chaotic !

And clearly t-0 > t-1 > t-2 ( Sort by thread creation time ). The final output is t-1 Most backward .

 Screenshot  2021-11-23  In the morning 12.26.44.png

What can we do to avoid confusion , Let's see below. .

Thread synchronization

Multithreading , That's more than one. Independent operating unit , Do the same thing at the same time .

Isn't multithreading done at the same time ? What else do you need to synchronize ?

Yes , Threads are called and executed at the same time , But each thread is independent of each other , Also competing with each other .

It's like there's... On the runway 3 An athlete , After the gunshot, run at the same time , But they Usually But not at the same time .

What does synchronization mean ?

Synchronization is the synchronization of three people running on this track , At any time , There's only one person on the runway .

Doesn't that sound ridiculous , How can multithreading not improve efficiency for multiple tasks ? Add a synchronization, not only one task is executed at a time , What else is multithreading .

unfortunately , That's what synchronization means , We sometimes say it completely , Synchronous mutual exclusion ! In conclusion, it is : Synchronization is a mechanism , It ensures that there is only one athlete on the track at any time . Technically, it's just , Synchronization guarantees Program data It is operated by only one thread at any time .

When we use the synchronization mechanism , Also looking for those that should be limited ’ runway ‘, The synchronization mechanism is used to ensure that there is only one... At any time on that runway ‘ Athletes ’ Run on it .

( The explanation is very clear , If you don't understand, you can ask your classmates to discuss the above sentences )

We understand the synchronization mechanism , Let's look at the lock .

threading.Lock Get sync lock

threading.Lock Is a class , We can use it to create a lock object .

What is a lock ?
A medium that maintains a synchronous mutual exclusion mechanism
Equivalent to a gate on the runway , Just open the door at a time and let one programmer in and run
Wrong , Athletes ( Programmers still need more exercise ).

If the lock breaks , The consequences can be imagined ( The following article will say ).

We will use the following code Lock Two functions of :

acquire function : Get the lock release function : Release the lock

As I said before , Plus the main thread , Is the total 6 Threads .

Run the following code to see :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/21 12:02  In the morning 
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat:  Lei Xuewei 
# @XueWeiTag: CodingDemo
# @File :
# @Project : hello

import threading
import datetime
import time

def dianzan_guanzhu(lock: threading.Lock):
    thread_name = threading.current_thread().getName()
    print(" The thread starts :", thread_name)
    now =
    name = "python Adorable new " + thread_name
    print("%s - %s name:%s" % (thread_name, now, name))
    result = " very good !" + name + "  Pay attention to Lei Xuewei , Learned to develop knowledge !"
    print("%s - %s result:%s" % (thread_name, now, result))
    return result

my_lock = threading.Lock()
for i in range(3):
    mythread = threading.Thread(name="t-" + str(i), target=lambda: dianzan_guanzhu(my_lock))
    print("mythread:", mythread)
    print("is_alive:", mythread.is_alive())
    ac = threading.active_count()
    print("active_count:", ac)
 Copy code 

Here are the results :

 Screenshot  2021-11-23  In the morning 12.46.35.png

We see that each thread has completed the task completely , There will be no output of three threads interspersed with each other .

Here beginners can feel the role of synchronization , effect .

Summary extension

The above is a thread coordination scheme .

Thread synchronization , Not at the same pace , It's synchronous and mutually exclusive !

The school committee also mentioned that synchronization and multithreading are contradictory , Keep looking back .

Here's a small question :

Yes? t-0 After the first line in the output function , Other output like activate_acount Etc ?

by the way , Some students often forget to pay attention to , Don't miss a lot of articles .

Besides, I like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column

Continuous learning and continuous development , I'm Lei Xuewei !
Programming is fun , The key is to understand the technology thoroughly .
Welcome to wechat , Like support collection !

copyright notice
author[Lei Xuewei],Please bring the original link to reprint, thank you.

Random recommended