python中的线程技术
#!/user/bin/env python
# @Time :2018/7/7 11:42
# @Author :PGIDYSQ
#@File :DaemonTest.py
import threading,time
# 1.线程的简单使用
# class MyThread(threading.Thread):
# def __init__(self,num,threadname):
# threading.Thread.__init__(self,name=threadname)
# self.num = num
# def run(self):
# time.sleep(self.num)
# print(self.num)
#
# t1 = MyThread(1,'t1')
# t2 = MyThread(5,'t2')
#
# t2.daemon = True
# print(t1.daemon)
# print(t2.daemon)
#
# t1.start()
# t2.start() #2.多线程使用,线程同步技术 # class MyThread2(threading.Thread):
# def __init__(self):
# threading.Thread.__init__(self)
# #重写run方法
# def run(self):
# global x
# #获取锁,
# lock.acquire()#相当于同步语块
# x = x+3
# print(x)
# #释放锁
# lock.release()
#
# lock = threading.RLock()
# #存放多个线程列表
# t12 = []
# #创建线程
# for i in range(10):
# #创建线程并添加到列表中
# t = MyThread2()
# t12.append(t)
# #多个线程互斥访问的变量
# x = 0
# #启动所有线程
# for i in t12:
# i.start()
#3.使用Condition实现生产者与消费者关系
from random import randint
from time import sleep
#自定义生产者线程类
class Producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
while True:
con.acquire()
if(len(x) == 10):
con.wait()
print('生产者等待中...')
else:
print('生产者:',end=' ')
x.append(randint(1,1000))
print('生产的数据:%s'%x)
sleep(1)
#唤醒等待条件的线程
con.notify()
#释放锁
con.release()
#自定义消费者线程类
class Consumer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
while True:
#获取锁
con.acquire()
if not x:
con.wait()
print("消费者等待中...")
else:
print('消费的数据:%s'%x.pop(0))
print('消费后剩余的数据:%s'%x)
sleep(2)
con.notify()
con.release() #创建Condition对象并测试
con = threading.Condition()
x = []
p = Producer("Producer")
c = Consumer("Consumer") # p.start()
# c.start()
# p.join()
# c.join()
#4.还有Queue对象,Event对象使用... #5.进程的使用
# from multiprocessing import Process
# import os
# from statistics import mean
#
# def f(name):
# print(os.getppid())
# print(name)
# if __name__ == '__main__':
# pro1 = Process(target=f,args=('yao',))
# pro1.start()
# pro1.join()
#6.计算二维数组每行的平均值
# x =[list(range(10)),list(range(20,30)),list(range(40,50)),list(range(70,90))]
# from multiprocessing import Pool
# from statistics import mean
# def f(x):
# return mean(x)#求平均值
# if __name__ == '__main__':
# with Pool(5) as p:
# print(p.map(f,x)) #7.使用管道实现进程间数据交换
# from multiprocessing import Process,Pipe
# def f(conn):
# conn.send('hello world')
# conn.close()
# if __name__ == "__main__":
# parent_conn,child_conn = Pipe()#创建管道对象,并设置接收端与发送端
# p = Process(target=f,args=(parent_conn,))#将管道的一方做为参数传递给子进程
# p.start()
# p.join()
# print(child_conn.recv())#接收管道发送方的信息
# child_conn.close()
#8.使用共享内存实现进程间数据的交换
# from multiprocessing import Process,Value,Array
# def f(n,a):
# n.value = 3.1415927
# for i in range(len(a)):
# a[i] = a[i] * a[i]
# if __name__ == "__main__":
# num = Value('d',0.0) #实型
# arr = Array('i',range(10)) #整型
# p = Process(target=f,args=(num,arr)) #创建进程对象
# p.start()
# p.join()
# print(num.value)
# print(arr[:])
#9.使用Manager对象实现进程间数据交互,Manager控制拥有list,dict,Lock,RLock,Semaphore,Condition,Event,Queue,Value等对象的服务端进程
# from multiprocessing import Manager,Process
# def f(d,l,t):
# d['name'] = 'Yaos'
# d['age'] = 34
# l.reverse()
# t.value=23
# if __name__ == "__main__":
# with Manager() as manager:
# d = manager.dict()
# l = manager.list(range(10))
# t = manager.Value('i',0)
# p = Process(target=f,args=(d,l,t))
# p.start()
# p.join()
# for item in d.items():
# print(item)
# print(l)
# print(t.value)
#10.进程同步技术与现场同步技术类似,可以使用Lock,Event对象
# from multiprocessing import Process,Event
# def f(e,i):
# if e.is_set():
# e.wait()
# print('hello world',i)
# e.clear()
# else:
# e.set()
# if __name__ == "__main__":
# e = Event()
# for num in range(6):
# Process(target=f,args=(e,num)).start()
#11.MapReduce框架的使用---大数据处理
#一种编程模型,用于大规模数据集(大于1TB)的并行计算
# import os,os.path,time
# '''大文件分割'''
# def FileSplit(sourceFile,targetFile):
# if not os.path.isfile(sourceFile):
# print(sourceFile,' does not File!')
# return
# if not os.path.isdir(targetFile):
# os.mkdir(targetFile)
# tempData = []
# number = 1000#切分后的每一个小文件包含number行数据
# fileNum = 1
# with open(sourceFile,'r',encoding='UTF-8') as srcFile:
# dataLine = srcFile.readline().strip()
# while dataLine:
# for i in range(number):
# tempData.append(dataLine)
# dataLine = srcFile.readline()
# if not dataLine:
# break
# desFile = os.path.join(targetFile,sourceFile[0:-4] + str(fileNum) + ".txt")
# with open(desFile,'a+',encoding='UTF-8') as f:
# f.writelines(tempData)
# tempData = []
# fileNum = fileNum + 1
#
# if __name__ == "__main__":
# FileSplit(sourceFile="test.txt",targetFile="test/SourceFileSplit") '''12.使用Map处理数据'''
# import os,re,threading,time
# def Map(sourceFile):
# if not os.path.exists(sourceFile):
# print(sourceFile,'does not exist')
# return
# pattern = re.compile(r'[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}')
# result = {}
# with open(sourceFile,'r',encoding='UTF-8') as srcFile:
# for dataLine in srcFile:
# r = pattern.findall(dataLine)#查找符合日期格式的字符串
# if r:
# # result.get(r[0],0):get()方法用于返回指定键的对应值,当键不存在时,返回指定特定的值;与setdefault()一样,当键不存在时,新增指定的值
# result[r[0]] = result.get(r[0],0) + 1
# desFile = sourceFile.replace('SourceFileSplit','MapFile')[0:-4] + '_map.txt'
# with open(desFile,'a+',encoding='UTF-8') as fp:
# for k,v in result.items():
# fp.write(k+':'+str(v)+'\n')
# if __name__ == "__main__":
# desFolder = 'test/SourceFileSplit'
# files = os.listdir(desFolder)
# def Main(i):
# Map(desFolder+'\\'+files[i])
# fileNumber = len(files)
# for i in range(fileNumber):#多线程处理
# t = threading.Thread(target=Main,args=(i,))
# t.start()
'''13.使用Reducer获取最终数据'''
# from os.path import isdir
# from os import listdir
#
# def Reduce(sourceFolder,targetFile):
# if not isdir(sourceFolder):
# print(sourceFolder,'does not exist.')
# return
# result = {}
# #仅处理匹配的文件
# allFiles = [sourceFolder + '\\' + f for f in listdir(sourceFolder) if f.endswith('_map.txt')]
# for f in allFiles:
# with open(f,'r',encoding='UTF-8') as fp:
# for line in fp:
# line = line.strip()
# if not line:
# continue
# key,value = line.split(':')
# result[key] = result.get(key,0) + int(value)
# with open(targetFile,'w',encoding='UTF-8') as fp:
# for k,v in result.items():
# fp.write(k+':'+str(v)+'\n\n')
# if __name__ == "__main__":
# Reduce('test\\MapFile','test\\result.txt') #14.优化上面MapRedurce处理,需要进行分割文件,直接使用Map,Reduce
# import os,re,time
# def Map(sourceFile):
# if not os.path.exists(sourceFile):
# print(sourceFile,' does not exist.')
# return
# pattern = re.compile(r'[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}')
# result = {}
# with open(sourceFile,'r',encoding='UTF-8') as srcFile:
# for dataLine in srcFile:
# r = pattern.findall(dataLine)
# if r:
# print(r[0],',',1)
# Map('test.txt')
#15.Redurce文件
# import os,sys
# def Reduce(targetFile):
# result = {}
# for line in sys.stdin:
# riqi,shuliang = line.strip().split(',')
# result[riqi] = result.get(riqi,0)+1
# with open(targetFile,'w',encoding='UTF-8') as fp:
# for k,v in result.items():
# fp.write(k+':'+str(v)+'\n')
# Reduce('result.txt')
本文旨在学习python中有关线程的基础知识,上述代码都是一个个相关的实例,仅供参考。
python中的线程技术的更多相关文章
- 理解 Python 中的线程
原地址:http://blog.jobbole.com/52060/ 本文由 伯乐在线 - acmerfight 翻译自 Akshar Raaj.欢迎加入技术翻译小组.转载请参见文章末尾处的要求. 我 ...
- Python中的线程和进程
引入进程和线程的概念及区别 threading模块提供的类: Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, l ...
- python中的线程锁
锁对象 原始锁是一个在锁定时不属于特定线程的同步基元组件.在Python中,它是能用的最低级的同步基元组件,由 _thread 扩展模块直接实现. 原始锁处于 "锁定" 或者 &q ...
- Python 中的线程-进程2
原文:https://www.cnblogs.com/i-honey/p/7823587.html Python中实现多线程需要使用到 threading 库,其中每一个 Thread类 的实例控制一 ...
- 【Python】解析Python中的线程与进程
基础知识 线程 进程 两者的区别 线程的类型 Python 多线程 GIL 创建多线程 线程合并 线程同步与互斥锁 可重入锁(递归锁) 守护线程 定时器 Python 多进程 创建多进程 多进程通信 ...
- Python之路-Python中的线程与进程
一.发展背景 任务调度 大部分操作系统(如Windows.Linux)的任务调度是采用时间片轮转的抢占式调度方式,也就是说一个任务执行一小段时间后强制暂停去执行下一个任务,每个任务轮流执行.任务执行的 ...
- python中的缓存技术
python缓存技术 def console(a,b): print('进入函数') return (a,b) print(console(3,'a')) print(console(2,'b')) ...
- python中杀死线程
有时候有这样的需要,在某种情况下,需要在主线程中杀死之前创建的某个线程,可以使用下面的方法,通过调用python内置API,在线程中抛出异常,使线程退出. import threading impor ...
- django 中的延迟加载技术,python中的lazy技术
---恢复内容开始--- 说起lazy_object,首先想到的是django orm中的query_set.fn.Stream这两个类. query_set只在需要数据库中的数据的时候才 产生db ...
随机推荐
- javaScript设计模式之面向对象编程(object-oriented programming,OOP)--寄生组合式继承
组合式继承:将类式继承同构造函数继承组合使用,但是存在一个问题,子类不是父类的实例,而子类的原型式父类的实例,所以才有了寄生组合式继承. 意思就是说,寄生就是寄生式继承,寄生式继承就是依托于原型继承, ...
- 『集群』001 Slithice 服务器集群 概述
Slithice 服务器集群 概述 Slithice是做什么的 Slithice 是一个 跨平台 的 分布式架构 框架: 旨在简化 分布式开发 的开发难度,节省 开发成本 和 后期维护成本: 并提供 ...
- 前端笔记之移动端&响应式(下)默认样式&事件&惯性抛掷&swiper&loaction对象
一.移动端默认样式 ·IOS和Android下触摸元素时出现半透明灰色遮罩 a,input,button{ -webkit-tap-highlight-color: transparent; } ·I ...
- 面向对象之七大基本原则(javaScript)
1. 前言 2. 单一职责 3. 开闭原则 4. 里氏替换 5. 依赖倒置 6. 接口隔离 7. 迪米特法则 8. 组合聚合复用原则 9. 总结 1. 前言 面向对象编程有自己的特性与原则,如果对于面 ...
- 如何快速高效简洁的打开软件 干净利索的windows快捷程序启动器
本文的主题是如何高效快捷的打开你想要打开的软件 本文介绍的应该是最简洁的一种方式,借助于windows内部的path进行设置 也可以认为是一种形式的windows应用启动器程序---win+R快速打开 ...
- 网站集群架构(LVS负载均衡、Nginx代理缓存、Nginx动静分离、Rsync+Inotify全网备份、Zabbix自动注册全网监控)--技术流ken
前言 最近做了一个不大不小的项目,现就删繁就简单独拿出来web集群这一块写一篇博客.数据库集群请参考<MySQL集群架构篇:MHA+MySQL-PROXY+LVS实现MySQL集群架构高可用/高 ...
- RAC(ReactiveCocoa)介绍(一)
最近在学习RAC,之前在iOS工作中,类之间的传值,无非是block.delegate代理.KVO和Notification等这几种方法.在RAC中,同样具备替代block.delegate代理.KV ...
- DSAPI WIN7磨砂+窗体投影组合
你可以使用DSAPI和DS控件库组合多种特效,以下是透明窗体+WIN7磨砂+窗体投影组合效果 设计界面 编写代码 Private Sub Form1_Load(sender As Object, e ...
- 系统设计Design For Failure思想
系统设计Design For Failure思想 Complex systems fail in spectacular ways. Failure isn't a question of if, b ...
- 通用mapper认识和用法
目录 0. 认识 1. 导包 2. mybatis的config文件:mybatis-mapper-config.xml 3. spring与mybatis整合配置文件:mybatis.xml 4. ...