-1

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.

Keldan Chapman
  • 665
  • 5
  • 21

1 Answers1

-1

You can use Threading module. Define function that you want to run in thread and run it then. Code should look like this:

import time
import random
import threading as th

def some_func():
    time.sleep(random.randint(1, 5))
    print('end')

print('foo') # Should be printed only once
t1 = th.Thread(target=some_func,)
t1.start()
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)
Raxodius
  • 109
  • 8
  • This does not answer the question. I need the new thread to remain where it is. Simply copy pasting the entire code into a function and targeting it with the thread will not work in my case. – Keldan Chapman Jan 12 '21 at 12:34
  • Then i dont understand what do you expect. What you mean by "new thread remain where it is"? Can you explain something more how should look the program flow? – Raxodius Jan 12 '21 at 16:55
  • I will update the question with a hopefully more clear example. – Keldan Chapman Jan 13 '21 at 08:31
  • I added an example. To put it simply, I want a normal thread, but instead of targeting another function, I want to target the function we are currently in, and to automatically jump to the current line. (The line after creating the new thread) – Keldan Chapman Jan 13 '21 at 08:41