Answer the question
In order to leave comments, you need to log in
Writing to 1 variable from two threads. How to properly process a queue in python?
For example, there is such a simplified construction with the launch of 2 threads and the simultaneous rewriting of one variable, as a result, a random is formed in the last line of the output.
import threading as th
lenAllData = 1000000
queueData = []
def threadAddQueue():
global queueData
# Симулируем заполнение очереди
for i in range(lenAllData):
queueData.append(i)
def threadProcQueue():
global queueData
queueProceed = []
# симулируем разбор очереди
while True:
if len(queueData) > 0:
queueProceed = queueProceed + queueData
queueData = []
print(f'Length {len(queueProceed)}, last value {queueProceed[-1]}')
# Запускаем и получаем рандом в выводе
if __name__ == '__main__':
th1 = th.Thread(target=threadAddQueue)
th1.start()
th2 = th.Thread(target=threadProcQueue)
th2.start()
Answer the question
In order to leave comments, you need to log in
In general, I decided this:
import threading as th
from collections import deque
lenAllData = 1000000
class ClassForQueue:
queueData = deque()
def threadAddQueue():
# Симулируем заполнение очереди
print('Start added to Queue')
for i in range(lenAllData):
ClassForQueue.queueData.append(i)
print('All added to Queue')
def threadProcQueue():
# симулируем разбор очереди
result = deque()
while True:
if len(ClassForQueue.queueData):
result.append(ClassForQueue.queueData.popleft())
if result[-1] == lenAllData - 1:
print(f'final! Length {len(result)}, last value {result[-1]}')
break
# Запускаем и получаем адекватные данные в выводе
if __name__ == '__main__':
th1 = th.Thread(target=threadAddQueue)
th1.start()
th2 = th.Thread(target=threadProcQueue)
th2.start()
The standard solution in all languages is either locking after receiving data, or lockfree primitives. In the last project, I used a dumb stream to get data and polls that simply return the current value. This made it possible to raise rps from a miserable 5 to 400
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question