I want to know if it is possible (and if so, then how) to create a new Thread without changing its 'location' in the code.
An example probably explains it better:
import time
import random
print('foo') # Should be printed only once
new_thread_here()
time.sleep(random.randint(1, 5))
print('end') # This should be printed twice (once per thread), each with a random sleep time (eg. 2 and 4 seconds)
Is there anyway to implement this, or anything similar??
In case it is relevant, my specific task involves building an asynchronous context manager, which would run the code within the context in a seperate thread while the main thread skipped it and continues on in the code.
Edit
Another example:
def foo():
print('First')
print('Second')
new_thread_here() # This is where I would make the new thread
print('Third') # This is where the new thread would start
foo()
print('Done')
Now, if we look at the expected results of the main thread:
>>> First
>>> Second
>>> Third
>>> Done
And now, lets look at the expected results of the second (created) thread. Consider that it starts directly after the new_thread_here()
call:
>>> Third
>>> Done
So the final output of the function would be (Assuming the threads run at the same speed):
>>> First
>>> Second
>>> Third
>>> Third
>>> Done
>>> Done
I am aware this might not be possible, but I am not an expert on thread handling so I wanted to ask here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…