python进程通信太垃圾、多线程无法并发_python 实用编程技巧 —— 多线程并发相关问题与解决技巧...

如何使用多线程

创建一个线程类来封装数据

from threading import Thread

from time import sleep

def handle(sid):

print('Download...(%d)' % sid)

sleep(2)

print('Convert to...(%d)' % sid)

class MyThread(Thread): # 自定义线程类

def __init__(self, sid):

# Thread.__init__(self)

super(MyThread, self).__init__() # 必须调用 父类的构造器 这是py2的语法,py3是super().__init__()

self.sid = sid # 使用类,能够更好的封装数据

def run(self): # 新建程序的入口点,和target类似

handle(self.sid) # 更常见的做法是将handle也做为这个类的方法

if __name__ == '__main__':

t = MyThread(1)

t.start()

t.join()

print('main thread')

如何实现线程间的通信

GIL

在每个进程中, 存在一把GIL, 该进程中的线程间共享GIL

多线程进行时, 只有有GIL的那个线程能运行

通过线程间快速 传递GIL, 达到表象上的多线程, 其实同一时间只有一个线程在工作

解决方案:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值