Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - How to create a new thread in the same code location. [python3]

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...