【python,threading】python多线程
使用多线程的方式
1、 函数式:使用threading模块threading.Thread(e.g target name parameters)
import time,threading
def loop():
print("thread %s is running..." % threading.current_thread().name)
n = 0
while n < 5:
n += 1
print("thread %s is running... n = %s" % (threading.current_thread().name,str(n)))
time.sleep(1)
print("thread %s is over..." % threading.current_thread().name) print("thread %s is running..." % threading.current_thread().name) ts = []
for i in range(5):
t = threading.Thread(target = loop, name = 'loopThread '+ str(i))
t.start()
ts.append(t)
for t in ts:
t.join()
print("thread %s is over..." % threading.current_thread().name)
多线程的输出:
thread MainThread is running...
thread loopThread 0 is running...
thread loopThread 0 is running... n = 1
thread loopThread 1 is running...
thread loopThread 1 is running... n = 1
thread loopThread 2 is running...
thread loopThread 2 is running... n = 1
thread loopThread 0 is running... n = 2
thread loopThread 1 is running... n = 2
thread loopThread 2 is running... n = 2
thread loopThread 0 is running... n = 3
thread loopThread 1 is running... n = 3
thread loopThread 2 is running... n = 3
thread loopThread 0 is running... n = 4
thread loopThread 1 is running... n = 4
thread loopThread 2 is running... n = 4
thread loopThread 0 is running... n = 5
thread loopThread 1 is running... n = 5
thread loopThread 2 is running... n = 5
thread loopThread 0 is over...
thread loopThread 1 is over...
thread loopThread 2 is over...
thread MainThread is over...
python中得thread的一些机制和C/C++不同:在C/C++中,主线程结束后,其子线程会默认被主线程kill掉。而在python中,主线程结束后,会默认等待子线程结束后,主线程才退出。
python对于thread的管理中有两个函数:join和setDaemon
join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。
setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死。【此段内容摘录自junshao90的博客】
2. 使用面向对象方式。创建子类继承自threading.Thread,需overwrite run方法
import time,threading
class threadTest(threading.Thread):
def __init__(self,tname):
threading.Thread.__init__(self)
self.name = tname
def run(self):
print("thread %s is running..." % threading.current_thread().name)
n = 0
while n < 5:
n += 1
print("thread %s is running... n = %s" % (threading.current_thread().name,str(n)))
time.sleep(1)
print("thread %s is over..." % threading.current_thread().name)
print("thread %s is running..." % threading.current_thread().name) for i in range(3):
t = threadTest('t' + str(i))
t.start()
t.join()
print("thread %s is over..." % threading.current_thread().name)
运行输出:
thread MainThread is running...
thread t0 is running...
thread t0 is running... n = 1
thread t0 is running... n = 2
thread t0 is running... n = 3
thread t0 is running... n = 4
thread t0 is running... n = 5
thread t0 is over...
thread t1 is running...
thread t1 is running... n = 1
thread t1 is running... n = 2
thread t1 is running... n = 3
thread t1 is running... n = 4
thread t1 is running... n = 5
thread t1 is over...
thread t2 is running...
thread t2 is running... n = 1
thread t2 is running... n = 2
thread t2 is running... n = 3
thread t2 is running... n = 4
thread t2 is running... n = 5
thread t2 is over...
thread MainThread is over...
3. lock
多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响。
而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把 内容给改乱了。
lock 对象:
acquire():负责取得一个锁。如果没有线程正持有锁,acquire方法会立刻得到锁。否则,它闲意态等锁被释放。一旦acquire()返回,调用它的线程就持有锁。
release(): 释放锁。如果有其他线程正等待这个锁(通过acquire()),当release()被效用的时候,它们中的一个线程就会
被唤醒
以下内容摘自“廖雪峰的官方网站”
balance为共享资源,多进程同时执行,一定概率结果为balance != 0[详细描述见原文]
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
使用threading.Lock()
import threading total = 0
lock = threading.Lock()
def change(n):
global total
total += n
total -= n def run_thread(n):
lock.acquire()
for i in range(100000):
change(n)
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(total)
4. 其他详细关于对进程的资料可参考
解决共享资源问题的:条件变量,同步队列
Vamei的博客Python标准库08 多线程与同步 (threading包)
片片灵感的博客Python多线程学习
【python,threading】python多线程的更多相关文章
- threading模块,python下的多线程
一.GIL全局解释器锁 In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple nativ ...
- python threading模块使用 以及python多线程操作的实践(使用Queue队列模块)
今天花了近乎一天的时间研究python关于多线程的问题,查看了大量源码 自己也实践了一个生产消费者模型,所以把一天的收获总结一下. 由于GIL(Global Interpreter Lock)锁的关系 ...
- 【python标准库学习】thread,threading(一)多线程的介绍和使用
在单个程序中我们经常用多线程来处理不同的工作,尤其是有的工作需要等,那么我们会新建一个线程去等然后执行某些操作,当做完事后线程退出被回收.当一个程序运行时,就会有一个进程被系统所创建,同时也会有一个线 ...
- python高级之多线程
python高级之多线程 本节内容 线程与进程定义及区别 python全局解释器锁 线程的定义及使用 互斥锁 线程死锁和递归锁 条件变量同步(Condition) 同步条件(Event) 信号量 队列 ...
- python 类变量 在多线程下的共享与释放问题
最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大 1.python 类变量 在多线程情况 下的 是共享的 2.python 类变量 在多线程情况 ...
- Python学习笔记- Python threading模块
Python threading模块 直接调用 # !/usr/bin/env python # -*- coding:utf-8 -*- import threading import time d ...
- python中的多线程【转】
转载自: http://c4fun.cn/blog/2014/05/06/python-threading/ python中关于多线程的操作可以使用thread和threading模块来实现,其中th ...
- python threading基础学习
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' """ python是支持多线程的,并 ...
- Python之FTP多线程下载文件之分块多线程文件合并
Python之FTP多线程下载文件之分块多线程文件合并 欢迎大家阅读Python之FTP多线程下载系列之二:Python之FTP多线程下载文件之分块多线程文件合并,本系列的第一篇:Python之FTP ...
- Python之FTP多线程下载文件之多线程分块下载文件
Python之FTP多线程下载文件之多线程分块下载文件 Python中的ftplib模块用于对FTP的相关操作,常见的如下载,上传等.使用python从FTP下载较大的文件时,往往比较耗时,如何提高从 ...
随机推荐
- LeetCode283:Move Zeros
Given an array nums, write a function to move all 0's to the end of it while maintaining the relativ ...
- 51Nod 1201 整数划分 (经典dp)
题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1201 题意不多说了. dp[i][j]表示i这个数划分成j个数 ...
- POJ1275Cashier Employment(查分约束系统)
链接1275Cashier Employment 题目大意就是说有一些人来应聘一个超级市场的工作,每个人的应聘的起始时间在0~23时之间,而超市在时间i需要R[i]个工作人员,而每个人的工作时间都是8 ...
- 编译安装-MySQL5.5
一.参数选项 1.目录选项 2.存储引擎选项 3.库文件加载选项 二.安装 1.环境准备 2.安装前的系统设置 3.安装执行 4.初始化数据库 5.注册为服务 6.加入环境变量 7.启动服务 8.重新 ...
- android 简易定时器
定时器 1.在android 应用开发当中,很多时候都要用到定时器,而要实现定时器更多的时候要用到两个类:Timer,和TimerTask 2.API对Timer的解释是:
- DBCP连接池介绍
DBCP连接池介绍 ----------------------------- 目前 DBCP 有两个版本分别是 1.3 和 1.4. DBCP 1.3 版本需要运行于 JDK 1.4-1.5 ,支持 ...
- JS原生方法实现jQuery的ready()
浏览器加载页面的顺序: 1. 解析HTML结构 2. 加载外部脚本和样式表文件 3. 解析并执行脚本代码 4. 构造HTML DOM模型==ready() 5. 加载图片等组件 6. 页面加载完毕== ...
- BZOJ 4318: OSU! 期望DP
4318: OSU! 题目连接: http://www.lydsy.com/JudgeOnline/problem.php?id=4318 Description osu 是一款群众喜闻乐见的休闲软件 ...
- 如何用C#语言构造蜘蛛程序
"蜘蛛"(Spider)是Internet上一种很有用的程序,搜索引擎利用蜘蛛程序将Web页面收集到数据库,企业利用蜘蛛程序监视竞争对手的网站并跟踪变动,个人用户用蜘蛛程序下载We ...
- Java虚拟机的启动与程序的执行
这篇文章是从 OpenJDK 源码的角度讲当我们执行了 java -classpath . hello 之后,java.exe 怎样从 main 函数開始运行,启动虚拟机,并运行字节码中的代码. 实验 ...