Python multithreading and coroutines

1. Multithreading

threading.Threadis Python's built-in threading module for creating and managing threads. Here's threading.Threadhow to use the function:

  1. Import threadingmodule:

 import threading
  1. 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 targetparameter is the specified executive function, argswhich 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 Trueif the thread is still running, otherwise it returns False.

     5. You can use namethe attribute to specify a name for the thread, for example:

my_thread.name = "MyThread"

     6. You can use daemonthe 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.Threadthe 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, asyncis 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.

asyncKeywords are often awaitused together with keywords. awaitThe 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 asyncthe and awaitkeywords, you can write asynchronous, non-blocking code to improve program efficiency. asyncioAt the same time, many asynchronous libraries and tools, such as modules and libraries, are also provided in the Python standard library, which aiohttpcan 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)

Guess you like

Origin blog.csdn.net/weixin_48144018/article/details/129990518