“This is the 20th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Official Python column # 42, stop! Don’t miss this zero-based article!

The previous two articles introduced the concept of threads and code demonstrations of multithreaded programs, but in multithreaded programs, they print independently of each other at a different time!

And t-0 > T-1 > T-2. It turns out that t-1 is the last.

What can we do to avoid confusion? Let’s see.

Thread synchronization

Multithreading, that is, multiple independent running units doing the same thing at the same time.

Doesn’t multithreading already do simultaneous execution? Why do we need to synchronize?

Yes, threads are invoked at the same time, but each thread is independent of and competing with each other.

It’s like having three runners on the track, starting at the same time after the gun goes off, but they usually don’t finish at the same time.

What does sync mean?

Synchrony is when there are three people running on the track plus synchrony, there’s only one person on the track at any given time.

As bizarre as it sounds, isn’t multithreading more efficient for multiple tasks? Add synchronization and only one task will be executed at a time. What about multithreading?

Unfortunately, synchronization is exactly what it means, and we sometimes say it more fully, synchronization is mutually exclusive! To summarize: synchronization is a mechanism that ensures that there is only one runner on the track at any one time. Technically, synchronization ensures that program data is handled by only one thread at a time.

When we use synchronization, we are also looking for ‘tracks’ that should be restricted and using synchronization to ensure that only one’ runner ‘is running on that track at any one time.

(The explanation is very clear, can not understand the students to discuss the above sentence)

Now that we know about synchronization, let’s look at locking.

Threading.lock Obtains the synchronization Lock

Threading.Lock is a class that we can use to create a Lock object.

What is a lock? A medium that maintains synchronous mutex is the equivalent of a racetrack with a gate that only opens to let in one programmer at a time.

If the lock is broken, you can imagine the consequences.

The following code will use two Lock functions:

Acquire function: acquire lock release function: release lock

As mentioned earlier, plus the main thread, there are six threads.

Run the following code to see:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @time: 2021/11/21 12:02 am
# @Author : LeiXueWei
# @csDN /Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello

import threading
import datetime
import time


def dianzan_guanzhu(lock: threading.Lock) :
    thread_name = threading.current_thread().getName()
    print("Thread started :", thread_name)
    now = datetime.datetime.now()
    name = "Python of new" + thread_name
    lock.acquire()
    print("%s - %s name:%s" % (thread_name, now, name))
    time.sleep(1)
    result = "Great! + name + "Pay attention to the thunder committee, learned to develop knowledge!"
    print("%s - %s result:%s" % (thread_name, now, result))
    lock.release()
    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())
    mythread.start()
    ac = threading.active_count()
    print("active_count:", ac)
Copy the code

Here is the result:

We see that each thread completes its task without having three threads interspersed with each other’s output.

Here beginners can feel the role of synchronization, the effect.

Conclusion extended

This is one thread coordination scheme.

Thread synchronization, is not the same pace, but synchronization mutually exclusive!

As mentioned above, synchronization and multithreading are incompatible, so read on.

Here’s a quick question:

T-0: activate_acount: activate_acount: activate_acount: activate_acount

By the way, some students often forget to pay attention to the articles, a lot of articles don’t miss.

If you are interested in Python, please check out the Basic Python column of the Committee or the Getting Started to Master Python column

Continuous learning and continuous development, I am Lei Xuewei! Programming is fun. The key is to get the technology right. Welcome to wechat, like support collection!