#!/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. Appium在Android7.0及以上系统运行时报错的解决方案

    背景:在使用Samsung S系列手机进行自动化测试时,发现同样脚本的情况下华为荣耀系列可以正常运行,最终发现差异在于Android7.0及以上系统和appium版本不匹配,需要升级appium.但需 ...

  2. Spring Cloud微服务系列文,Hystrix与Eureka的整合

    和Ribbon等组件一样,在项目中,Hystrix一般不会单独出现,而是会和Eureka等组件配套出现.在Hystrix和Eureka整合后的框架里,一般会用到Hystrix的断路器以及合并请求等特性 ...

  3. ProgressWheelDialogUtil【ProgressWheel Material样式进度条对话框】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 简单封装网络请求时的加载对话框以及上传.下载文件的进度加载对话框. 效果图 代码分析 ProgressWheel : 自定义view ...

  4. springboot~openfeign从此和httpClient说再见

    在微服务设计里,服务之间的调用是很正常的,通常我们使用httpClient来实现对远程资源的调用,而这种方法需要知识服务的地址,业务接口地址等,而且需要等他开发完成后你才可以去调用它,这对于集成开发来 ...

  5. [开源]Entity Framework 6 Repository 一种实现方式

    在使用Entity Framework这种ORM框架得时候,一般结合Repository仓储形式来处理业务逻辑:虽然这种模式带来很多好处,但是也会引发一些争议,在此抛开不谈,小弟结合项目经验来实现一下 ...

  6. RabbitMQ在Windows环境下的安装与使用

    Windows下安装RabbitMQ 环境配置 部署环境 部署环境:windows server 2008 r2 enterprise 官方安装部署文档:http://www.rabbitmq.com ...

  7. 基于 DataLakeAnalytics 做跨地域的数据分析

    在阿里云上,很多客户的应用都是多地域部署的, 比如在北京(cn-beijing)的地域部署一个应用让北方的客户访问快一点,同时在杭州(cn-hangzhou)地域部署一份让南方的客户访问快一点.多地域 ...

  8. Docker进阶之四:镜像管理

      一.什么是镜像? 简单说,Docker镜像是一个不包含Linux内核而又精简的Linux操作系统. 二.镜像从哪里来? Docker Hub是由Docker公司负责维护的公共注册中心,包含大量的容 ...

  9. centos7+rsyslog+loganalyzer+mysql 搭建rsyslog日志服务器

    一.简介 在centos7系统中,默认的日志系统是rsyslog,它是一类unix系统上使用的开源工具,用于在ip网络中转发日志信息,rsyslog采用模块化设计,是syslog的替代品. 1.rsy ...

  10. .NET(C#、VB)移动开发——Smobiler平台控件介绍:TextTabBar控件

    TextTabBar控件 一.          样式一 我们要实现上图中的效果,需要如下的操作: 从工具栏上的“Smobiler Components”拖动一个TextTabBar控件到窗体界面上 ...