First, let's define the producer and consumer functions:
def produce():
# Produce some data
return "Produced data: " + str(random.randint(1, 10))
def consume():
# Consume the produced data
produced_data = produce()
print(f"Consumed data: {produced_data}")
Next, we'll create a thread for the producer and another thread for the consumer:
We'll start the producer thread first, then the consumer thread:
producer_thread.start()
consumer_thread.start()
Here's the main part of the code that implements the producer-consumer pattern using threads:
# Producer thread
def produce():
# Produce some data
return "Produced data: " + str(random.randint(1, 10))
# Consumer thread
def consume():
# Consume the produced data
produced_data = produce()
print(f"Consumed data: {produced_data}")
# Create threads
producer_thread = threading.Thread(target=produce)
consumer_thread = threading.Thread(target=consume)
# Start threads
producer_thread.start()
consumer_thread.start()
# Wait for threads to finish
producer_thread.join()
consumer_thread.join()
This code will produce some data in the producer thread, and consume that data in the consumer thread. The producer and consumer threads will run concurrently, allowing the producer to produce data and the consumer to consume it simultaneously.
Note that this is a very basic implementation of the producer-consumer pattern, and in a real-world scenario, you would likely need to handle errors and other edge cases. Additionally, this implementation uses the threading module to create and manage threads, but there are other ways to implement concurrency in Python, such as using the asyncio module.