
아래는 Queue의 동기화 문제를 해결하는 방법입니다.
Queue의 lock() 메서드는 쓰레드가 Queue에 데이터를 삽입하거나 삭제하는 동안 다른 쓰레드가 Queue에 접근하는 것을 막습니다. 하지만 Queue의 lock() 메서드는 쓰레드 간의 데이터 공유를 위한 동기화 메서드가 아닙니다.
아래는 Queue의 동기화 문제를 해결하는 방법입니다.
1. `asyncio.Lock()`을 사용하여 쓰레드 간의 데이터 공유를 위한 동기화 메서드를 만들 수 있습니다.
#hostingforum.kr
python
import asyncio
lock = asyncio.Lock()
async def producer(queue):
async with lock:
for i in range(10):
await queue.put(i)
print(f"생산자: {i}")
async def consumer(queue):
async with lock:
while True:
item = await queue.get()
print(f"소비자: {item}")
if item == 9:
break
2. `asyncio.Semaphore()`을 사용하여 쓰레드 간의 데이터 공유를 위한 동기화 메서드를 만들 수 있습니다.
#hostingforum.kr
python
import asyncio
semaphore = asyncio.Semaphore(1)
async def producer(queue):
async with semaphore:
for i in range(10):
await queue.put(i)
print(f"생산자: {i}")
async def consumer(queue):
async with semaphore:
while True:
item = await queue.get()
print(f"소비자: {item}")
if item == 9:
break
3. `asyncio.Queue()`의 `get_nowait()` 메서드를 사용하여 쓰레드 간의 데이터 공유를 위한 동기화 메서드를 만들 수 있습니다.
#hostingforum.kr
python
import asyncio
async def producer(queue):
for i in range(10):
await queue.put(i)
print(f"생산자: {i}")
async def consumer(queue):
while True:
try:
item = await queue.get_nowait()
print(f"소비자: {item}")
except asyncio.QueueEmpty:
break
if item == 9:
break
위 코드에서 Queue의 동기화 문제를 해결하는 방법은 여러 가지가 있습니다. 하지만 가장 좋은 방법은 `asyncio.Lock()`을 사용하는 것입니다.
2025-08-08 18:06