Python basics (producer and consumer mode, threadingLocal)

Stack

First-in-last-out
is also implemented by the queue module. The
first-in-last-out counter-column (stack)
declaration format:

	# 创建一个栈
	q = queue.LeftQueue()
	# 进栈
	q.put()
	# 出栈
	q.get()

Producer and consumer model

Using producer and consumer patterns in concurrent programming can solve most concurrency problems. This mode improves the overall data processing speed
of the program by balancing the working capabilities of production threads and consumer threads. Example:

import threading
import queue

num = 0
# 生产者
def func1(name):
	global num
	num += 1
	print(f"{name}完成{num}号包子")
	q.put(f"{num}号包子")

# 消费者
def func2(name):
	res = q.get()
	print(f"{name}获取了{res}号包子")

if __name__ == '  main  ':
	# 创建了一个队列
	q = queue.Queue()
	# 创建两个线程
	t1 = threading.Thread(target=func1, args=("王大厨",))
	t2 = threading.Thread(target=func1, args=("小王",))
	t1.start()
	t2.start()

The consumer is the process that consumes the data, the
producer is the process that produces the data

What is the producer and consumer model

The producer-consumer model uses a container to solve the problem of strong coupling between the producer and the consumer. The producer and the consumer do not communicate directly with each other, but communicate through the blocking queue, so the producer finishes producing the data After that, instead of waiting for the consumer to process, it is directly thrown to the blocking queue. The consumer does not ask the producer for data, but directly fetches it from the blocking queue. The blocking queue is equivalent to a buffer, which balances the processing capabilities of the producer and the consumer.

Why use the producer and consumer model

In multi-threading, if the producer produces data too fast and the consumer consumes the data very slowly, there will be an oversupply phenomenon. The producer has to wait for the consumer to consume the data before it can continue to produce. The speed of data is too fast, and the producer cannot keep up with the consumption speed, and there will be a shortage of demand. At this time, consumers need to wait for the producer. In order to solve this problem, the producer and consumer model is introduced.

threadingLocal

ThreadingLocal is equivalent to binding a database for each thread. Each thread can access its own database to get the data it wants, which solves the problem of parameter transfer between various functions in a thread.
example:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44781625/article/details/108610754