【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下载较大的文件时,往往比较耗时,如何提高从 ...
随机推荐
- [iOS微博项目 - 2.4] - 重新安排app启动步骤
github: https://github.com/hellovoidworld/HVWWeibo A.app启动步骤 1.加入了授权步骤之后,最先要判断app内是否已经登陆了账号 2.在程序启 ...
- Tomcat 系统架构与设计模式,第 2 部分: 设计模式分析(转载)
简介: 这个分为两个部分的系列文章研究了 Apache Tomcat 服务器的系统架构以及其运用的很多经典设计模式.第 1 部分 分析了 Tomcat 的工作原理,第 2 部分将分析 Tomcat 中 ...
- jquery操作复选框(checkbox)
1.获取单个checkbox选中项(三种写法)$("input:checkbox:checked").val()或者$("input:[type='checkbox']: ...
- CountDownLatch和CyclicBarrier的区别
[CountDownLatch.CyclicBarrier和Semaphore]http://www.cnblogs.com/dolphin0520/p/3920397.html [CountDo ...
- [hihoCoder]#1039 : 字符消除
Description 小Hi最近在玩一个字符消除游戏.给定一个只包含大写字母"ABC"的字符串s,消除过程是如下进行的: 1)如果s包含长度超过1的由相同字母组成的子串,那么这些 ...
- Oracle复制表结构和表数据
一, 复制表结构及数据 create table z_xudebiao_test as select * from v_topic v where v.adddate > to_date('20 ...
- extjs tablepanel 高度自适应有关问题
extjs tablepanel 高度自适应问题 项目中为了给客户好点的功能切换体验,想到了用extjs的tabpanel 在页面中用了tabpanel后,高度新打开的tab页的iframe 的高度总 ...
- 解决 Cocos2d-x 中 Android.mk 手动添加源文件
转自:http://blog.csdn.net/ypfsoul/article/details/8909178 Makefile Android.mk 引发的思索 在我们编写 Android 平台 c ...
- Don’t use Suspend and Resume, but don’t poll either.
http://www.paradicesoftware.com/blog/2014/02/dont-use-suspend-and-resume-but-dont-poll-either/ Don’t ...
- 【机试题】c# 是否是素数,找出比它大的第一个素数
题目: 输入一个自然数 判断是否是素数,是素数则提示是素数,否则找出比它大的第一个素数 代码: Console.WriteLine("请输入任意一个自然数."); string n ...