https://www.cnblogs.com/wj-1314/p/8263328.html

threading 模块

先上代码:

 import time, threading

 def loop():
print("thread %s is running..." %threading.current_thread().name)
n = 0
while n<5:
n += 1
print('thread %s >>> %s'%(threading.current_thread().name, n))
time.sleep(1)
print("thread %s ended." %threading.current_thread().name) def loop1():
x = 1
while x <3:
print(x,"loop1的线程")
x += 1
time.sleep(2) if __name__ == "__main__":
print("thread %s is running ..." %threading.current_thread().name)
t = threading.Thread(target = loop, name = "LoopThread")
t1 = threading.Thread(target = loop1)
t.start()
t1.start()
t.join()
t1.join()
print("thread %s ended." % threading.current_thread().name) """
thread MainThread is running ...
thread LoopThread is running...1
thread LoopThread >>> 1
loop1的线程
thread LoopThread >>> 2
2thread LoopThread >>> 3
loop1的线程
thread LoopThread >>> 4
thread LoopThread >>> 5
thread LoopThread ended.
thread MainThread ended. """

由于任何进程默认就会启动一个线程,我们把该线程称为主线程,主线程又可以启动新的线程,Python的threading模块有个threading.current_thread() 获取当前线程的实例。

但是有些情况下,多线程会产生场景上的错误,比如

import time, threading

# 假定这是你的银行存款:
balance = 0 def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n def run_thread(n):
for i in range(100000):
change_it(n) t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

结果有时会报错

如果我们要确保balance计算正确,就要给change_it()上一把锁,当某个线程开始执行change_it()时,我们说,该线程因为获得了锁,因此其他线程不能同时执行change_it(),只能等待,直到锁被释放后,获得该锁以后才能改。由于锁只有一个,无论多少线程,同一时刻最多只有一个线程持有该锁,所以,不会造成修改的冲突。创建一个锁就是通过threading.Lock()来实现:

import time, threading
lock = threading.Lock() # 假定这是你的银行存款:
balance = 0 def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n def run_thread(n):
for i in range(100000): lock.acquire()
try:
change_it(n)
finally:
lock.release() t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

python基础===多线程的更多相关文章

  1. python --- 基础多线程编程

    在python中进行多线程编程之前必须了解的问题: 1. 什么是线程? 答:线程是程序中一个单一的顺序控制流程.进程内一个相对独立的.可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程 ...

  2. Python基础-多线程与多进程

    一,线程与进程之间的关系:(从知乎上看到的) 一个必须知道的事实:执行一段程序代码,实现一个功能的过程介绍 ,当得到CPU的时候,相关的资源必须也已经就位,就是显卡啊,GPS啊什么的必须就位,然后CP ...

  3. python基础之多线程与多进程(一)

    并发编程? 1.为什么要有操作系统? 操作系统,位于底层硬件与应用软件之间 工作方式:向下管理硬件,向上提供接口 2.多道技术? 不断切换程序. 操作系统进程切换: 1.出现IO操作 2.固定时间 进 ...

  4. Python基础补充(二) 多核CPU上python多线程并行的一个假象【转】

    在python上开启多个线程,由于GIL的存在,每个单独线程都会在竞争到GIL后才运行,这样就干预OS内部的进程(线程)调度,结果在多核CPU上: python的多线程实际是串行执行的,并不会同一时间 ...

  5. python基础:多进程、多线程

    一.定义和区别 1.一个任务就是一个进程,进程就是资源的集合.比如打开浏览器,启动一个进程.当一个进程需要干很多事的时候,就需要执行多个子任务,这些子任务就是线程. 2.线程是包含在进程中的,每个进程 ...

  6. Python之路3【第一篇】Python基础

    本节内容 Python简介 Python安装 第一个Python程序 编程语言的分类 Python简介 1.Python的由来 python的创始人为吉多·范罗苏姆(Guido van Rossum) ...

  7. python基础——多重继承

    python基础——多重继承 继承是面向对象编程的一个重要的方式,因为通过继承,子类就可以扩展父类的功能. 回忆一下Animal类层次的设计,假设我们要实现以下4种动物: Dog - 狗狗: Bat ...

  8. 第一篇:python基础

    python基础   python基础 本节内容 python起源 python的发展史 为什么选择python3 第一个python程序 变量定义 表达式和运算符 用户输入 流程控制 判断 流程控制 ...

  9. Day1 - Python基础1 介绍、基本语法、流程控制

    Python之路,Day1 - Python基础1   本节内容 Python介绍 发展史 Python 2 or 3? 安装 Hello World程序 变量 用户输入 模块初识 .pyc是个什么鬼 ...

随机推荐

  1. 【题解】CF#983 E-NN country

    首先,我们从 u -> v 有一个明显的贪心,即能向上跳的时候尽量向深度最浅的节点跳.这个我们可以用树上倍增来维护.我们可以认为 u 贪心向上跳后不超过 lca 能跳到 u' 的位置, v 跳到 ...

  2. BZOJ2111:[ZJOI2010]排列计数——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=2111 https://www.luogu.org/problemnew/show/P2606#su ...

  3. BZOJ1060:[ZJOI2007]时态同步——题解

    http://www.lydsy.com/JudgeOnline/problem.php?id=1060 https://www.luogu.org/problemnew/show/P1131 小Q在 ...

  4. LOJ6346:线段树:关于时间 ——题解

    https://loj.ac/problem/6346 题目还是没法粘贴…… 一道蛮不错的题. 老年选手困了30min后才想要推式子实在是太懒了…… 我们可以对每次更新列表看成系数*x即可. 举例:第 ...

  5. Mac安装mysqldb

    一. 安装mysql (一)下载地址 https://pan.baidu.com/s/1slw50LZ 安装成功后,在系统偏好设置里有MySQL图标,可以启动或关闭MySQL 二. Mysql roo ...

  6. Vue推荐资料

    推荐博文(我是看过,才敢说的偶): 基础教学: 菜鸟语法教程:https://cn.vuejs.org/v2/guide/syntax.html  http://www.runoob.com/vue2 ...

  7. caffe环境的搭建(Ubuntu14.04 64bit,无CUDA,caffe在CPU下运行)

    1. 安装BLAS : $ sudo apt-get install libatlas-base-dev 2. 安装依赖项: $ sudo apt-get install libprotobuf-de ...

  8. mybatis <where>、<set>、<trim>、<sql>、<foreach>标签的使用

    转:http://www.cnblogs.com/lixiujie/p/5766669.html <resultMap>标签的使用:这个类似于hibernte用于映射我们创建的vo对象与数 ...

  9. Leetcode 380. 常数时间插入、删除和获取随机元素

    1.题目描述 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构. insert(val):当元素 val 不存在时,向集合中插入该项. remove(val):元素 val 存在时 ...

  10. matlab求一个矩阵中各元素出现的个数(归一化)

    function [m,n] = stamatrix(a) %网上找到的方法,感觉很巧妙 x=a(:); x=sort(x); d=diff([x;max(x)+1]); count = diff(f ...