【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下载较大的文件时,往往比较耗时,如何提高从 ...
随机推荐
- oracle学习 二(持续更新中)
oracle数据库的启动停止 以oracle用户身份登录 登录后输入以下命令: oracle-> sqlplus /nolog SQL*Plus: Release 9.2.0.1.0 - Pro ...
- MetaQ安装部署文档
一.MetaQ安装部署情况: 地点 IP Broker ID Master/Slave Slave ID:Group 合肥 192.168.52.23 Slave 1:meta-slave-group ...
- poj 1247 The Perfect Stall 裸的二分匹配,但可以用最大流来水一下
The Perfect Stall Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 16396 Accepted: 750 ...
- hdoj 5335 Walk Out
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5335 #include<stdio.h> #include<cstring> ...
- Magento开发文档(一):Magento入门
开始之前,首先声明下,Magento开发者手册由Alan Storm发表在Magento官方网站上.总共分八个部分,由浅入深的介绍了Magento的MVC架构及Magento中使用的比较特殊的EAV模 ...
- JS Flex交互:html嵌套Flex(swf)
一.html页面嵌套Flex需要用到 swfobject.js swfobject的使用是非常简单的,只需要包含 swfobject.js这个js文件,然后在DOM中插入一些简单的JS代码,就能嵌入F ...
- 永久改动redhat的default route
1,能够用route命令暂时改动: route add default gw <gateway ip> 2, 通过改动/etc/sysconfig/network 文件永久改动: 脚本: ...
- c# 轻量级 ORM 框架 之 Model解析 (四)
关于orm框架设计,还有必要说的或许就是Model解析了,也是重要的一个环节,在实现上还是相对比较简单的. Model解析,主要用到的技术是反射了,即:把类的属性与表的字段做映射. 把自己的设计及实现 ...
- embed 隐藏播放器显示
昨天在页面做音频播放的时候,客户要求仅仅有声音.不显示播放器. 百度搜到解决方法: <embed id="embed_sound_id" src="test.mp3 ...
- 一步步学Mybatis-实现多表联合查询(4)
上一章节中我们已经完成了对单表的CRUD操作,接下来今天这一讲讲述的是关于Mybatis在多表查询时候的应用,毕竟实际业务中也是多表的联合查询比较多嘛~ 还记得最一开始我们新建过一张Website表吗 ...