2019独角兽企业重金招聘Python工程师标准>>>

多线程

import threadingdef main():print(threading.active_count())print(threading.enumerate())print(threading.current_thread())if __name__ == '__main__':main()D:\PythonTest>python test.py
1
[<_MainThread(MainThread, started 4124)>]
<_MainThread(MainThread, started 4124)>
线程数
print(threading.active_count())线程名
print(threading.enumerate())当前线程数
print(threading.current_thread())添加线程
added_thread = threading.Thread()
added_thread.start()

添加线程add thread

import threadingdef thread_job():print("This is an added Thread,number is %s"% threading.current_thread())def main():added_thread = threading.Thread(target =thread_job)added_thread.start()if __name__ == '__main__':main()
import threading
import timedef thread_job():print('T1 start\n')for i in range(10):time.sleep(0.1)print('T1 finish\n')def main():added_thread = threading.Thread(target =thread_job,name = 'T1')added_thread.start()print('all done\n')if __name__ == '__main__':main()D:\PythonTest>python test.py
T1 startall doneT1 finish

join功能

等待
added_thread.join()
import threading
import timedef thread_job():print('T1 start\n')for i in range(10):time.sleep(0.1)print('T1 finish\n')def main():added_thread = threading.Thread(target =thread_job,name = 'T1')added_thread.start()added_thread.join()print('all done\n')if __name__ == '__main__':main()D:\PythonTest>python test.py
T1 startT1 finishall done
  • 比较
import threading
import timedef thread_job():print('T1 start\n')for i in range(10):time.sleep(0.1)print('T1 finish\n')def T2_job():print('T2 start\n')print('T2 finish\n')def main():added_thread = threading.Thread(target = thread_job,name = 'T1')thread2 = threading.Thread(target =T2_job,name = 'T2')added_thread.start()thread2.start()print('all done\n')if __name__ == '__main__':main()D:\PythonTest>python test.py
T1 startT2 startT2 finishall doneT1 finish
import threading
import timedef thread_job():print('T1 start\n')for i in range(10):time.sleep(0.1)print('T1 finish\n')def T2_job():print('T2 start\n')print('T2 finish\n')def main():added_thread = threading.Thread(target = thread_job,name = 'T1')thread2 = threading.Thread(target =T2_job,name = 'T2')added_thread.start()thread2.start()added_thread.join()print('all done\n')if __name__ == '__main__':main()D:\PythonTest>python test.py
T1 startT2 startT2 finishT1 finishall done
import threading
import timedef thread_job():print('T1 start\n')for i in range(10):time.sleep(0.1)print('T1 finish\n')def T2_job():print('T2 start\n')print('T2 finish\n')def main():added_thread = threading.Thread(target = thread_job,name = 'T1')thread2 = threading.Thread(target =T2_job,name = 'T2')added_thread.start()thread2.start()thread2.join()print('all done\n')if __name__ == '__main__':main()D:\PythonTest>python test.py
T1 startT2 startT2 finishall doneT1 finish

queue功能

import threading
import time
from queue import Queuedef job(l,q):for i in range(len(l)):l[i] = l[i] ** 2q.put(l)def multithreading():q = Queue()threads = []data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]for i in range(4):t = threading.Thread(target = job,args = (data[i],q))t.start()threads.append(t)for thread in threads:thread.joinresults = []for _ in range(4):results.append(q.get())print(results)if __name__ == '__main__':multithreading()

GIL

import threading
import time
from queue import Queue
import copydef job(l,q):res = sum(l)q.put(res)def multithreading(l):q = Queue()threads = []for i in range(4):t = threading.Thread(target = job,args = (copy.copy(l),q),name = 'T%i'%i)t.start()threads.append(t)[t.join() for t in threads]total = 0for _ in range(4):total += q.get()print(total)def normal(l):total = sum(l)print(total)if __name__ == '__main__':l = list(range(1000000))s_t = time.time()normal(l * 4)print('normal:',time.time() - s_t)s_t = time.time()multithreading(l)print('multithreading:',time.time() - s_t)D:\PythonTest>python test.py
1999998000000
normal: 0.13805341720581055
1999998000000
multithreading: 0.16271591186523438

锁loop

import threading
import time
from queue import Queuedef job1():global Afor i in range(10):A += 1print('join1',A)def job2():global Afor i in range(10):A += 10print('join2',A)if __name__ == '__main__':A = 0t1 = threading.Thread(target = job1)t2 = threading.Thread(target = job2)t1.start()t2.start()t1.join()t2.join()D:\PythonTest>python test.py
join1 1
join1 2
join1 13
join1 14
join1 15
join1 16
join1 17
join1 18
join1 19
join1 20
join2 12
join2 30
join2 40
join2 50
join2 60
join2 70
join2 80
join2 90
join2 100
join2 110
import threading
import time
from queue import Queuedef job1():global A,locklock.acquire()for i in range(10):A += 1print('join1',A)lock.release()def job2():global A,locklock.acquire()for i in range(10):A += 10print('join2',A)lock.release()if __name__ == '__main__':lock = threading.Lock()A = 0t1 = threading.Thread(target = job1)t2 = threading.Thread(target = job2)t1.start()t2.start()t1.join()t2.join()D:\PythonTest>python test.py
join1 1
join1 2
join1 3
join1 4
join1 5
join1 6
join1 7
join1 8
join1 9
join1 10
join2 20
join2 30
join2 40
join2 50
join2 60
join2 70
join2 80
join2 90
join2 100
join2 110

转载于:https://my.oschina.net/hellopasswd/blog/2396054

【Python】多线程#181101相关推荐

  1. Python多线程(3)——Queue模块

    Python多线程(3)--Queue模块 Queue模块支持先进先出(FIFO)队列,支持多线程的访问,包括一个主要的类型(Queue)和两个异常类(exception classes). Pyth ...

  2. python统计csv行数_对Python 多线程统计所有csv文件的行数方法详解

    如下所示: #统计某文件夹下的所有csv文件的行数(多线程) import threading import csv import os class MyThreadLine(threading.Th ...

  3. c++主线程等待子线程结束_简单明了的 Python 多线程来了 | 原力计划

    作者 | 万里羊责编 | 王晓曼出品 | CSDN博客线程和进程计算机的核心是CPU,它承担了所有的计算任务,就像是一座工厂在时刻运行.如果工厂的资源有限,一次只能供一个车间来使用,也就是说当一个车间 ...

  4. python3 多线程_图解|为什么 Python 多线程无法利用多核

    (给Python开发者加星标,提升Python技能) 来源:后端技术指南针 1.全局解释锁 如题: Python的多线程为什么不能利用多核处理器? 全局解释器锁(Global Interpreter ...

  5. python多线程下的信号处理程序示例

    下面是一个网上转载的实现思路,经过验证,发现是可行的,就记录下来. 思路 python多线程中要响应Ctrl+C的信号以杀死整个进程,需要: 1.把所有子线程设为Daemon: 2.使用isAlive ...

  6. Python 多线程抓取网页 牛人 use raw socket implement http request great

    Python 多线程抓取网页 - 糖拌咸鱼 - 博客园 Python 多线程抓取网页 最近,一直在做网络爬虫相关的东西. 看了一下开源C++写的larbin爬虫,仔细阅读了里面的设计思想和一些关键技术 ...

  7. python 多线程编程之_thread模块

    python 多线程编程之_thread模块 参考书籍:python核心编程 _thread模块除了可以派生线程外,还提供了基本的同步数据结构,又称为锁对象(lock object,也叫原语锁.简单锁 ...

  8. python多线程读取文件的问题_Python多线程同步---文件读写控制方法

    1.实现文件读写的文件ltz_schedule_times.py #! /usr/bin/env python #coding=utf-8 import os def ReadTimes(): res ...

  9. c语言多线程转python多线程,真正的python 多线程!一个修饰符让你的多线程和C语言一样快...

    > Python 多线程因为GIL的存在,导致其速度比单线程还要慢.但是近期我发现了一个相当好用的库,这个库只需要增加一个修饰符就可以使原生的python多线程实现真正意义上的并发.本文将和大家 ...

  10. python 多线程和协程结合_一文讲透 “进程、线程、协程”

    本文从操作系统原理出发结合代码实践讲解了以下内容: 什么是进程,线程和协程? 它们之间的关系是什么? 为什么说Python中的多线程是伪多线程? 不同的应用场景该如何选择技术方案? ... 什么是进程 ...

最新文章

  1. 设计模式——单例模式(Singleton)
  2. Hessian源码分析(java)
  3. JPTagView-多样化的标签View
  4. Attribute is missing the Android namespace prefix
  5. 使用windows server backup备份还原hyper-v 3.0虚拟机
  6. 《Head First设计模式》第九章(1)迭代器模式
  7. VS2008中使用JSONCPP方法小结
  8. Spring Data JPA 从入门到精通~关键字列表
  9. C#基础系列——语法
  10. linux命令zip打包,linux下zip命令打包与解包
  11. 华为否认降低手机产量传闻:全球生产水平正常 无明显调整
  12. C#中Dictionary的用法及用途(转)
  13. Kafka开源转商业实践,助力车主无忧系统稳健 | 凌云时刻
  14. k3梅林刷官改变砖_K3 op强刷回官改变砖,TTL救砖也不行,请大神分析下是不是要换内存了...
  15. You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations
  16. 服装系统mysql设计_服装行业ERP系统的设计与实现-店铺模块(SSH,MySQL)(含录像)
  17. 【转】深度技术分析“为什么ios比android流畅”
  18. Cisco Packet Tracer入门实验之双机互联
  19. 在vue里引入使用Ag-grid表格插件
  20. Excel画图多个线条样式设置(在黑白下区分各个线条的作用)

热门文章

  1. 志宇-Spring源码分析
  2. android studio 汉化
  3. 51单片机 Proteus仿真 8X8点阵英文流水显示 汉字流水显示
  4. 千寻浏览器 v1.0 beta1 官方版
  5. openwrt-MT7688 拨号上网(亲身经历)
  6. 阿里云ECS搭建的PPTP内网通,但无法访问外网,无法转发。
  7. NRF52832基于SDK15.3 S332协议栈实现adv和rsp广播厂商自定义数据
  8. FZU 2092 收集水晶
  9. 辣根过氧化物酶HRP标记链霉亲和素说明书
  10. 基于sip的语音对讲 Demo