Python的asyncio 多线程

  --  多线程、进程、协程是什么就不讲了,(就是你理解的一边呼吸,一边看文章)

仅解决问题的话,下边两篇不用看,

Python 中的 async await 概念-CSDN博客

再深一点的看这个

Python中的多线程、进程、协程、threading、asyncio-CSDN博客



我们这里需求很简单,就是让2个方法都运行!!



这里要用的就是asyncio 库

我们这里要让 loop_func 和 my_func 同时执行,需要3步:

 

第一步,把2个方法前边都加上 async  声明为特殊的func(咱也不道能不能叫多线程方法,问就是特殊不一样)。

第二步,在2个func中各自加 一个锚点 await , 这个就是标志运行到这里就可以执行其他应用了。(这个就很重要)

第三步,创建任务,用loop 执行起来。


   ---------------------------


那么就这么写:

完整代码如下:


import time
import asyncio

if __name__ == '__main__':

# 定义func 1
    async def loop_func():
        while True:
            for i in range(0,100):
                print("this is loop func runing----",i)

                # 整个锚点
                await asyncio.sleep(3)

# 定义另一个func

    async def my_func():
        print("this is my_func running...")
        while True:
            for i in range(0,100):
                print("this is my_func runing----",i)

                # 再整个锚点
                await asyncio.sleep(3)

# 搞个task 任务, run起来

    loop = asyncio.get_event_loop()
    tasks = [
        my_func(),
        loop_func(),
    ]
    loop.run_until_complete((asyncio.gather(*tasks)))

其中绿色的是关键句子。

就这么简单,之前因为循环体没加锚点,就高低没有并行起来, 浏览器都查冒烟了没找到问题,最后还得是神奇海螺啊! 艹

相关推荐

  1. Python线线使用

    2024-03-15 23:12:03       66 阅读
  2. python线

    2024-03-15 23:12:03       42 阅读
  3. python 线

    2024-03-15 23:12:03       27 阅读
  4. python线使用

    2024-03-15 23:12:03       52 阅读
  5. Python线使用实践

    2024-03-15 23:12:03       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 23:12:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 23:12:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 23:12:03       87 阅读
  4. Python语言-面向对象

    2024-03-15 23:12:03       96 阅读

热门阅读

  1. 【leetcode】点名

    2024-03-15 23:12:03       39 阅读
  2. c++中的动态内存分配

    2024-03-15 23:12:03       38 阅读
  3. 【力扣】121. 买卖股票的最佳时机

    2024-03-15 23:12:03       40 阅读
  4. 24计算机考研调剂 | 大连海事大学轮机工程学院

    2024-03-15 23:12:03       43 阅读
  5. 记一下mysql安装过程中遇到的报错解决

    2024-03-15 23:12:03       43 阅读
  6. 【Go】探索Go语言中的panic和recover

    2024-03-15 23:12:03       44 阅读
  7. Halcon的了解

    2024-03-15 23:12:03       55 阅读