They way I understand your question you implicitly assuming some kind of multi threading or multi tasking. The easiest way however is keeping close to the name of your function and use a generator pattern:
def number_generator():
while True:
value = random.randint(1,100)
time.sleep(0.5)
yield value
gen = number_generator()
for num in gen:
# do something
print(num)
If you want to have the generator and worker run concurrently, you can use asyncio
. This makes sense if wour worker also needs some time e.g. to fetch something from a socket. In this wait time the generator can now already fetch the next job.
import random
import asyncio
class my_async_generator():
def __init__(self):
self.counter = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.counter >= 10:
raise StopAsyncIteration
await asyncio.sleep(1)
self.counter += 1
value = random.randint(1,100)
return value
async def worker(item):
await asyncio.sleep(5)
print(item)
async def do_async_stuff():
tasks = []
async for num in my_async_generator():
tasks.append(asyncio.create_task(worker(num)))
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(do_async_stuff())
Then you still have multi-tasking, which in the context of cpython ist not so much helpfull due to the GIL (global interpreter lock) and multi-processing. But for that you will need some kind of communication between the threads, because they don't share the same memory space anymore.