python线程、协程,了解一下

定义一个线程

import os
import  time,threading,multiprocessing

def thread_run():
    print(threading.get_ident(),'ident')
    print(os.getpid() , '=pid ')
    print(os.getppid(), '=ppid')

def run (name):
    time.sleep(2)
    print('hello',name)
    t = threading.Thread(target=thread_run,)
    t.start()

if __name__ == '__main__':
    for i in range(10):
        #args  是一个list
        #开启多线程
        p = multiprocessing.Process(target=run,args=('liu',))
        p.start()

再定义一个线程

import threading
import os
class A(threading.Thread):
    def __init__(self,s):
        self.s = s
        threading.Thread.__init__(self)

    def run(self):
        for i in range(111):
            print(self.s,threading.current_thread(),i,os.getppid(),os.getpid())


t1 = A('apple')
t1.start()

定义一个协程

'''
异步io
协程
微线程
用户态的的轻量级线程
拥有自己的寄存器上下文和栈
能保留上次的调用状态

无需上下文切换的开销
无需原子操作锁定及同步
高并发
高扩展
低成本

无法利用CPU多核资源

单线程内实现高并发的操作


执行多个方法
遇到io操作进行切换

'''

from greenlet import greenlet
import os

# 封装好的协程



def run():
    print('runing')
    print(os.getppid())
    g2.switch()  #切换到run2
    print(os.getpid())
    g2.switch()

def run2():
    print('run2ing')
    print(os.getppid())
    g1.switch()
    print(os.getppid())
    print('end')

g1 = greenlet(run)
g2 = greenlet(run2)

g1.switch()  #进行切换

#遇到io 自动切换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值