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

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

Previous articles have covered threads and thread safety in detail, as well as some programs under the multithreading error, thread safety modification.

Is there a magic solution to the threading/concurrency problem?

Yes, it’s a Queue.

What is a queue?

Like a queue, a line from the beginning to the end, and people can continue to queue behind, that’s a queue.

What the committee wants to talk about here is the class Queue, which is a class in the Queue built-in module.

Import queue q = queue.queue (5) # create a queue of infinite length without passing a number 0 or <0Copy the code

It provides many functions, and we use the following functions more often:

  • Get: Gets and removes the header element
  • Put: Adds elements to the end of the queue
  • Qsize: Gets the length of the queue
  • Empty: The queue is empty. No one else is in the queue
  • Full: Queue is full.

It looks boring, but the committee drew the following picture to show it:

This queue was put three times, put in order: continuous learning, continuous development, I lei Xueyi. The queue length is 3

Queue operations enter/exit/check the queue status

The committee prepared the following code:

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


import queue

q = queue.Queue(5)

print("Student committee fan Queue:", q)
print("Empty team, student committee fan queue size:", q.qsize())
print("Empty queue?", q.empty())
for i in range(5):
    q.put(i)

print("Full line?", q.full())
print("Full, student committee fan queue size:", q.qsize())

while not q.empty():
    print("Fan %s give it a thumbs up!" % q.get())
print("Finally, the size of the fan queue:", q.qsize())
Copy the code

This code creates a queue of length 5.

Then a loop filled the queue, followed by another queue, and fans voted “like”.

Here’s how it works:

Isn’t that easy?

Good news, Queue is a thread-safe class

The previous study committee showed several articles, encounter the following code (repeatedly read and write shared variables) results are always unexpected dependence!

amount = 100
def transfer(money) :
    global amount
    for i in range(100000):
        amount += money
Copy the code

Is there a problem if we read and write to the queue repeatedly?

Instead, write a code to check:

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


import queue
import threading

xuewei_fans_q = queue.Queue()


def transfer(money) :
    for i in range(100000):
        xuewei_fans_q.put(money)
        xuewei_fans_q.get()


# Create 4 tasks to add more attention to the committee/take off the fan (or hope you future stars of programming to learn and make progress together!)
t_group = []
for i in range(10):
    t = threading.Thread(target=lambda: transfer(-1))
    t_group.append(t)
    t.start()
    t = threading.Thread(target=lambda: transfer(1))
    t_group.append(t)
    t.start()
    t = threading.Thread(target=lambda: transfer(-1))
    t_group.append(t)
    t.start()
    t = threading.Thread(target=lambda: transfer(1))
    t_group.append(t)
    t.start()

for t in t_group:
    t.join()
print("-" * 16)
print("Active threads :", threading.active_count())
print("Active thread :", threading.current_thread().name)
# add data to queue repeatedly, remove data, queue finally clear zero
print("Student committee fan Queue :", xuewei_fans_q.qsize())
Copy the code

No matter how many times it is run, the queue (hopefully the black pink queue) is a 0 element.

conclusion

This committee shared a thread safe Queue, which is very important!

The front spent a lot of space to explain some of the problems and solutions of multithreading, very troublesome.

But the Queue class is thread-safe, and this one is verified, so be sure to stick with it.

Although the queue displayed is a fan queue, the committee still hopes that you will learn from it and make progress together!

In the next article, students will share how to use queue to transform the transfer procedure and solve the problem of the wrong amount of transfer gracefully.

By the way, if you like Python, please check out the Committee’s Python Basics column or Python Getting Started to Master 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!