#!/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中的线程技术的更多相关文章

  1. 理解 Python 中的线程

    原地址:http://blog.jobbole.com/52060/ 本文由 伯乐在线 - acmerfight 翻译自 Akshar Raaj.欢迎加入技术翻译小组.转载请参见文章末尾处的要求. 我 ...

  2. Python中的线程和进程

    引入进程和线程的概念及区别 threading模块提供的类:   Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, l ...

  3. python中的线程锁

    锁对象 原始锁是一个在锁定时不属于特定线程的同步基元组件.在Python中,它是能用的最低级的同步基元组件,由 _thread 扩展模块直接实现. 原始锁处于 "锁定" 或者 &q ...

  4. Python 中的线程-进程2

    原文:https://www.cnblogs.com/i-honey/p/7823587.html Python中实现多线程需要使用到 threading 库,其中每一个 Thread类 的实例控制一 ...

  5. 【Python】解析Python中的线程与进程

    基础知识 线程 进程 两者的区别 线程的类型 Python 多线程 GIL 创建多线程 线程合并 线程同步与互斥锁 可重入锁(递归锁) 守护线程 定时器 Python 多进程 创建多进程 多进程通信 ...

  6. Python之路-Python中的线程与进程

    一.发展背景 任务调度 大部分操作系统(如Windows.Linux)的任务调度是采用时间片轮转的抢占式调度方式,也就是说一个任务执行一小段时间后强制暂停去执行下一个任务,每个任务轮流执行.任务执行的 ...

  7. python中的缓存技术

    python缓存技术 def console(a,b): print('进入函数') return (a,b) print(console(3,'a')) print(console(2,'b')) ...

  8. python中杀死线程

    有时候有这样的需要,在某种情况下,需要在主线程中杀死之前创建的某个线程,可以使用下面的方法,通过调用python内置API,在线程中抛出异常,使线程退出. import threading impor ...

  9. django 中的延迟加载技术,python中的lazy技术

    ---恢复内容开始--- 说起lazy_object,首先想到的是django orm中的query_set.fn.Stream这两个类. query_set只在需要数据库中的数据的时候才 产生db ...

随机推荐

  1. GlideNewDemo【Glide4.7.1版本的简单使用以及圆角功能】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 简单记录下Glide4.7.1版本的使用和实现圆角方案. 注意:关于详细使用请仔细阅读<官方指南>. 效果图 使用步骤 ...

  2. 『集群』003 Slithice 最简分布式(多个客户端,一个独立服务端)

    Slithice 最简分布式(多个客户端,一个独立服务端) 案例Demo 展示: 我们搭建一个 可以 独立运行 的 服务端:然后 多个客户端 并发链接 这个 服务端 完成 分布式逻辑: 服务器 独立运 ...

  3. springboot~mockMvc和asciidoctor生成基于TDD的API文档

    API文档是前端与后端快速开发,减少沟通成本的必要条件,有一份完善的文档是很必要的,由通过测试来生成文档的好处就是:测试数据有了,测试返回结果有了,而且可以对这些字段进行说明,很清晰,在springb ...

  4. DotNetCore跨平台~2.0提前发布喽

    回到目录 提前1个多月把2.0发布出来了,小微真的把持不住了,哈哈! windows上安装 http://mp.weixin.qq.com/s/ueJdhaBBCHga0sQlVD6YiQ https ...

  5. 爸爸又给Spring MVC生了个弟弟叫Spring WebFlux

    情景引入 很早之前,Java就火起来了,是因为它善于开发和处理网络方面的应用. Java有一个爱好,就是喜欢制定规范标准,但自己又不善于去实现. 反倒是一些服务提供商使用它的规范标准来制造应用服务器而 ...

  6. Docker进阶之一:Docker介绍与体系结构

    一.  Docker是什么 Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源,基于Linux内核的cgroup,namespace,Union FS 等技术, ...

  7. Springboot 系列(十三)使用邮件服务

    在我们这个时代,邮件服务不管是对于工作上的交流,还是平时的各种邮件通知,都是一个十分重要的存在.Java 从很早时候就可以通过 Java mail 支持邮件服务.Spring 更是对 Java mai ...

  8. 使用SSL安全证书和nginx配置将域名HTTPS化

    一.在阿里云后台申请免费版证书: 二.在域名解析里面添加记录: 三.提交审核: 四.等待审核通过后,下载nginx证书: 五.按照文档修改nginx配置文件: https://help.aliyun. ...

  9. ITSA(IT Strategy and Architecture)方法介绍

    Architecture Capability – At a Glance Architectural coherence part1 Architectural coherence part2 SA ...

  10. Hibernate框架_搭建第一个Hibernate框架

    一.eclipse搭建 A.创建动态web项目 New-->Dynamic web project(web project) B.导入jar包 1.数据库驱动包 2.hibernate开发必须j ...