![]() |
|---|
| © thepythoncode.com |
由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址
Tutorial from RealPython[1]
Python threading allows you to have different parts of your program run concurrently and can simplify your design. If you’ve got some experience in Python and want to speed up your program using threads, then this tutorial is for you
What’s a Threading?
Threading is a separate flow of execution. In bash, you can run a background process by adding a symbol & at the end of commands. In python, we can achieve this with the example below.
As you might expect, if you run the codes below, thread_function(3) will be started at the end of thread_function(4)
import threadingimport timedef thread_function(Time):for i in range(Time):time.sleep(i)print(i)thread_function(4)thread_function(3)
0123012
But if we execute it in a threading or background process, they can run simultaneously.
- thread_function(4)+ x = threading.Thread(target=thread_function, args=(4,))+ x.start()+ # x.join()thread_function(3)
0011223
This is how we expect the background process, or daemon threads, to be performed.
join()
Some times, we’d like waiting for the threads. By doing so, we can call .join() to do so.
By uncomment x.join(), we can get the same result as the first.
import threadingimport timedef thread_function(Time):for i in range(Time):time.sleep(i)print(i)x = threading.Thread(target=thread_function, args=(4,))x.start()x.join()thread_function(3)
0123012
Working in a loop
threads = list()for Time in range(5):x = threading.Thread(target=thread_function, args=(Time,))threads.append(x)x.start()
0000111223
ThreadPoolExecutor
import threadingimport timeimport concurrent.futuresdef thread_function(Time):for i in range(Time):time.sleep(i)print(i,"from", Time)print(Time, "is Down")if __name__ == "__main__":with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:executor.map(thread_function, range(10))
0 is Down0 from 10 from 21 is Down0 from 30 from 41 from 22 is Down0 from 51 from 41 from 31 from 52 from 42 from 33 is Down0 from 61 from 62 from 53 from 44 is Down0 from 72 from 61 from 73 from 52 from 73 from 64 from 55 is Down0 from 83 from 71 from 84 from 62 from 84 from 73 from 85 from 66 is Down0 from 91 from 95 from 72 from 94 from 83 from 95 from 86 from 77 is Down4 from 96 from 85 from 96 from 97 from 88 is Down7 from 98 from 99 is Down
The code creates a ThreadPoolExecutor as a context manager, telling it how many worker threads it wants in the pool. It then uses .map() to step through an iterable of things, in your case range(3), passing each one to a thread in the pool.[1:2]
TEST
import threading, timedef sleep():time.sleep(30)print("sleep is down")x = threading.Thread(target=test, args=())x.start()x = threading.Thread(target=test, args=())x.is_alive()
Enjoy~
由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址
GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗

