1. Multithreading
threading.Thread
is Python's built-in threading module for creating and managing threads. Here's threading.Thread
how to use the function:
-
Import
threading
module:
import threading
-
To create a new thread, you need to define a function as the execution body of the thread, for example:
def my_func(arg1, arg2):
# do something
pass
my_thread = threading.Thread(target=my_func, args=(arg1, arg2))
Here target
parameter is the specified executive function, args
which is the parameter passed to the executive function, and these parameters must be passed in tuple form. After a thread is created, it can be start()
started using the method:
my_thread.start()
3. You can use join()
the method to wait for the thread to finish executing. For example:
my_thread.join()
join()
The method blocks the current thread until the called thread finishes executing.
4. You can use is_alive()
the method to check whether the thread is still running, for example:
if my_thread.is_alive():
print("Thread is still running.")
else:
print("Thread has finished.")
This method returns True
if the thread is still running, otherwise it returns False
.
5. You can use name
the attribute to specify a name for the thread, for example:
my_thread.name = "MyThread"
6. You can use daemon
the attribute to set the thread as a daemon thread, for example:
my_thread.daemon = True
A daemon thread is a thread that exits automatically when the main thread exits, without waiting for the thread to finish executing. If daemon thread is set to True
, the main thread will not wait for this thread to finish executing.
This is threading.Thread
the basic usage of . When using threads, please pay attention to thread safety and the use of locks to avoid thread conflicts and data race problems.
2. Coroutine
In Python, async
is a keyword used to create coroutines. Coroutine is a lightweight concurrent programming method that can implement asynchronous operations in a single thread to improve program performance and responsiveness.
async
Keywords are often await
used together with keywords. await
The keyword is used to wait for a coroutine to complete and return the result without blocking the current thread, allowing the thread to process other tasks.
By using async
the and await
keywords, you can write asynchronous, non-blocking code to improve program efficiency. asyncio
At the same time, many asynchronous libraries and tools, such as modules and libraries, are also provided in the Python standard library, which aiohttp
can help developers write asynchronous programs more conveniently.
import time
import asyncio
async def fun(n):
# 在真实使用场景中,这里的asyncio.sleep替换成支持协程的方法
await asyncio.sleep(1)
print("{} is done!".format(n))
# 使用协程 1.02s
t1 = time.perf_counter()
loop = asyncio.get_event_loop()
tasks = []
for i in range(1000):
tasks.append(fun(i))
loop.run_until_complete((asyncio.wait(tasks)))
t2 = time.perf_counter()
print(t2 - t1)