多线程应用-类(thread)
在对class thread加锁时,锁无法正常应用,函数方式没问题。
在使用class thread方法时,并发后的查询结果不对,函数方式没问题。
# -*- coding: UTF-8 -*-
from time import ctime,sleep
import threading,datetime
from Queue import Queue class pdc(threading.Thread):
def __init__(self,t_name):
threading.Thread.__init__(self,name=t_name)
#self.name='aaa' #此时self还不是Thread,为string格式
def run(self): #run()方法继承于threading,需要重写定义自己的内容
self.setName('b'+str(i)) #self.setName('bbb') #此时self是Thread,可以通过 print dir(self) 查看所具有的属性/方法
print '%s: %s is producing %d to the queue.' %(ctime(),self.getName(),i)
sleep(1) if __name__ == '__main__':
threads=[]
for i in range(5):
t = pdc('p'+str(i))
t.start()
threads.append(t)
for t in threads:
t.join()
返回结果:
Fri Apr 15 17:19:22 2016: b1 is producing 1 to the queue.
Fri Apr 15 17:19:22 2016: b1 is producing 1 to the queue.
Fri Apr 15 17:19:22 2016: b2 is producing 2 to the queue.
Fri Apr 15 17:19:22 2016: b4 is producing 4 to the queue.
Fri Apr 15 17:19:22 2016: b4 is producing 4 to the queue.
生产者-消费者模型(Thread-Queue):
# -*- coding: UTF-8 -*-
from time import ctime,sleep
import threading,datetime
from Queue import Queue class pdc(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self)
self.data = queue
self.name = t_name
def run(self): #run()方法继承于threading,需要重写定义自己的内容
tname = self.name
for i in range(5):
#print self.name
nn = tname + str(i)
self.setName(nn) #self.setName('bbb') #此时self是Thread,可以通过 print dir(self) 查看所具有的属性/方法
print '%s: %s is producing %d to the queue.' %(ctime(),self.getName(),i)
self.data.put(nn)
sleep(1)
print '%s: %s pdc finished!' %(ctime(),self.getName()) class cum(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self)
self.data = queue
self.name = t_name
def run(self):
tname = self.name
for i in range(5):
nn = tname + str(i)
self.setName(nn)
val = self.data.get()
print '%s: %s in consuming %d in the queue is consumed.' %(ctime(),self.getName(),i)
sleep(2)
print '%s: %s cum finished!' %(ctime(),self.getName()) if __name__ == '__main__':
queue = Queue()
producer = pdc('p',queue)
consumer = cum('c',queue)
producer.start()
consumer.start()
producer.join()
consumer.join() # print queue.qsize()
# while not queue.empty():
# print queue.get_nowait()
返回结果:
Mon Apr 18 10:05:26 2016: p0 is producing 0 to the queue.
Mon Apr 18 10:05:26 2016: c0 in consuming 0 in the queue is consumed.
Mon Apr 18 10:05:27 2016: p1 is producing 1 to the queue.
Mon Apr 18 10:05:28 2016: p2 is producing 2 to the queue.
Mon Apr 18 10:05:28 2016: c1 in consuming 1 in the queue is consumed.
Mon Apr 18 10:05:29 2016: p3 is producing 3 to the queue.
Mon Apr 18 10:05:30 2016: p4 is producing 4 to the queue.Mon Apr 18 10:05:30 2016: c2 in consuming 2 in the queue is consumed.
Mon Apr 18 10:05:31 2016: p4 pdc finished!
Mon Apr 18 10:05:32 2016: c3 in consuming 3 in the queue is consumed.
Mon Apr 18 10:05:34 2016: c4 in consuming 4 in the queue is consumed.
Mon Apr 18 10:05:36 2016: c4 cum finished!
生产者消费者模型,直接将queue定义为global,实际同上:
from time import ctime,sleep
import threading,datetime
from Queue import Queue
global queue class pdc(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self) def run(self): #run()方法继承于threading,需要重写定义自己的内容
for i in range(5): nn = 'qq_' + str(i)
print '%s: producing %s to the queue.' %(ctime(),nn)
queue.put(nn) #将生成出来的数据放入到queue中
sleep(0.1)
print '%s pdc finished!' %(ctime()) class cum(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self) def run(self):
for i in range(5):
val = queue.get() #从queue中取数据进行消费
print '%s: consuming %s. the last number of queue is %d' %(ctime(),val,queue.qsize())
sleep(1)
print '%s consume finished!' %(ctime()) if __name__ == '__main__':
queue = Queue()
producer = pdc(queue)
consumer = cum(queue)
producer.start()
consumer.start()
producer.join()
consumer.join()
返回:
Sun May 22 14:34:38 2016: producing qq_0 to the queue.
Sun May 22 14:34:38 2016: consuming qq_0. the last number of queue is 0
Sun May 22 14:34:39 2016: producing qq_1 to the queue.
Sun May 22 14:34:39 2016: producing qq_2 to the queue.
Sun May 22 14:34:39 2016: producing qq_3 to the queue.
Sun May 22 14:34:39 2016: producing qq_4 to the queue.
Sun May 22 14:34:39 2016 pdc finished!
Sun May 22 14:34:39 2016: consuming qq_1. the last number of queue is 3
Sun May 22 14:34:40 2016: consuming qq_2. the last number of queue is 2
Sun May 22 14:34:41 2016: consuming qq_3. the last number of queue is 1
Sun May 22 14:34:42 2016: consuming qq_4. the last number of queue is 0
Sun May 22 14:34:43 2016 consume finished!
多线程获取服务器信息(启动多个线程获取服务器信息放到quque中,启动一个线程从queue中获取数据进行处理,如写入数据库):
#-*- coding: UTF-8 -*-
import subprocess,cjson,threading
from Queue import Queue class P_infor(threading.Thread): #定义生产者,执行serverinfoj.ps1脚本(该脚本返回值为json字符串),获取服务器信息(dict),并放到queue中。
def __init__(self,lock,queue,IP):
threading.Thread.__init__(self)
self.psf = 'E:\\serverinfoj.ps1'
self.IP = IP
self.lock = lock
self.queue = queue
def run(self):
getinforchild = subprocess.Popen(['powershell.exe',self.psf,self.IP],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while getinforchild.poll() == None:
rsts = getinforchild.stdout.readlines()
if len(rsts) <> 0:
infor = cjson.decode(rsts[0])
if infor["Status"] == 'Success':
#print infor["Infors"]
with self.lock:
self.queue.put(infor["Infors"])
else:
print infor["Status"] class c_infor(threading.Thread): #定义消费者,从queue中取出服务器信息
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
try:
qq = self.queue.get(timeout=20)
print qq
except:
break if __name__ == '__main__':
IPS = ['10.160.30.50','10.160.30.51','10.160.25.48','10.160.26.50']
lst = IPS
tnum = 4 #定义线程数量
tcn = 1 #定义消费者进程数量
lock = threading.Lock()
queue = Queue() for i in range(0,len(lst),tnum):
threadsp=[]
for IP in lst[i:i+tnum]:
tp=P_infor(lock,queue,IP)
tp.start()
threadsp.append(tp) if tcn == 1: #消费者进程只启动一次
tc=c_infor(queue)
tc.start()
tcn = 0 for tp in threadsp:
tp.join()
tc.join()
附,serverinfoj.ps1脚本内容:
param($server)
#定义获取计算机信息的函数
Function GetServerInfo ($server,$account,$serverpass)
{ If (Test-Connection $server -count 2 -quiet)
{
$UserName = $account
$Password = ConvertTo-SecureString $serverpass -AsPlainText –Force
$cred = New-Object System.Management.Automation.PSCredential($UserName,$Password)
$session = New-PSSession -ComputerName $server -Credential $cred $system = Invoke-Command -Session $session -ScriptBlock {Get-WmiObject -Class Win32_ComputerSystem}
If ($?)
{
#获取计算机域名、型号
$domainname = $system.Domain
$model = $system.Model #获取计算机IP地址,取IP和gw不为空的网卡IP地址
#$ip = gwmi Win32_NetworkAdapterConfiguration -computer $server -Credential $cred |?{$_.ipaddress -ne $null -and $_.defaultipgateway -ne $null}
#$ipaddr = $system.Name #获取操作系统版本
$os = Invoke-Command -Session $session -ScriptBlock {Get-WmiObject -Class Win32_OperatingSystem} #获取操作系统版本
$os_caption = $os.Caption
If ($os_caption.Contains("Server 2008 R2 Enterprise"))
{$os_caption_s = "Win2008"}
ElseIf ($os_caption.Contains("Server 2003 Enterprise"))
{$os_caption_s = "Win2003"}
Else {$os_caption_s = $os.Caption}
$osversion = $os_caption_s + " " + $os.OSArchitecture.Substring(0,2) + "bit" #获取CPU名称、单颗CPU核心数量*CPU个数
$cpus = Invoke-Command -Session $session -ScriptBlock {Get-WmiObject -Class win32_processor}
$cpucount = 0
Foreach ($cpu in $cpus)
{
If ($cpu.DeviceID -ne $null)
{$cpucount += 1}
}
$cpunamecore = $cpu.name+" "+[string]$cpu.NumberOfLogicalProcessors + '*' + [string]$cpucount + "C" #获取内存大小
$memorys = Invoke-Command -Session $session -ScriptBlock {Get-WmiObject -Class Win32_PhysicalMemory}
#$memorylist = $null
$memorysize_sum = $null
Foreach ($memory in $memorys)
{
#$memorylist += ($memory.capacity/1024/1024/1024).tostring("F1")+"GB + "
[int]$memorysize_sum_n += $memory.capacity/1024/1024/1024
}
$memorysize_sum = [string]$memorysize_sum_n + "GB" #获取磁盘信息
$disks = Invoke-Command -Session $session -ScriptBlock {Get-WmiObject -Class Win32_Diskdrive}
$disklist = $null
#$disksize_sum = $null
Foreach ($disk in $disks)
{
$disklist += ($disk.deviceid.replace("\\.\PHYSICALDRIVE","Disk") +":" + [int]($disk.size/1024/1024/1024)+"GB ")
#$disksize_sum+=$disk.size
} #获取计算机序列号、制造商
$bios = Invoke-Command -Session $session -ScriptBlock {Get-WmiObject -Class Win32_BIOS}
$sn = $bios.SerialNumber
If ($sn.Substring(0,6) -eq "VMware")
{$sn = "VMware"}
If ($bios.Manufacturer.contains("Dell"))
{$manufacturer = "Dell"}
Elseif ($bios.Manufacturer.contains("HP"))
{$manufacturer = "HP"}
Elseif ($bios.Manufacturer.contains("Microsoft"))
{
$manufacturer = "Microsoft"
$sn = "Hyper-V"
}
Else {$manufacturer = $bios.Manufacturer}
$type = $manufacturer + " " + $model $serverinfoj = @"
{"Status": "Success","Infors": {"ServerName": "$env:ComputerName","IP": "$Server","OSVersion": "$osversion","MemorySize": "$memorysize_sum", "CPU": "$cpunamecore","DomainName": "$domainname","DISK": "$disklist","SN": "$sn","Type":"$type"}}
"@ }
Else
{
$serverinfoj = @"
{"Status": "RPC Failed"}
"@
}
}
Else
{
$serverinfoj = @"
{"Status": "Unreachable"}
"@
}
#$serverinfo = ConvertFrom-Json -InputObject $serverinfoj
Return $serverinfoj
}
$account = 'u\admin'
$serverpass = 'password'
GetServerInfo $server $account $serverpass
多线程应用-类(thread)的更多相关文章
- C++实现多线程类Thread
Windows编程中创建线程的常见函数有:CreateThread._beginthread._beginthreadex.据说在任何情况下_beginthreadex都是较好的选择. _begint ...
- “全栈2019”Java多线程第二章:创建多线程之继承Thread类
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...
- 【C#多线程】1.Thread类的使用及注意要点
Thread随便讲讲 因为在C#中,Thread类在我们的新业务上并不常用了(因为创建一个新线程要比直接从线程池拿线程更加耗费资源),并且在.NET4.0后新增了Task类即Async与await关键 ...
- 多线程之继承Thread类及多线程内存分析
*创建多线程的一种方式:继承Thread类 * java.lang.Thread是描述多线程的类,要实现多线程程序,一种方式就是继承Thread类 * 1.创建一个类Mythread让其extends ...
- java多线程系类:基础篇:02常用的实现多线程的两种方式
本章,我们学习"常用的实现多线程的2种方式":Thread 和 Runnable.之所以说是常用的,是因为通过还可以通过java.util.concurrent包中的线程池来实现多 ...
- java多线程系类:基础篇:01基本概念:
这个系类的内容全部来源于http://www.cnblogs.com/skywang12345/p/3479024.html.特别在此声明!!! 本来想直接看那位作家的博客的,但还是复制过来. 多线程 ...
- Java多线程——ThreadLocal类
一.概述 ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是threadlocalvariable(线程局部变量).也许把它命名 ...
- c#通用多线程基类,以队列形式
c#通用多线程基类,以队列形式 个人原创.欢迎转载.转载请注明出处.http://www.cnblogs.com/zetee/p/3487084.html 多线程这个概念大家都很熟悉,对于winfor ...
- Java多线程4:Thread中的静态方法
一.Thread类中的静态方法 Thread类中的静态方法是通过Thread.方法名来调用的,那么问题来了,这个Thread指的是哪个Thread,是所在位置对应的那个Thread嘛?通过下面的例子可 ...
- java 如何使用多线程调用类的静态方法?
1.情景展示 静态方法内部实现:将指定内容生成图片格式的二维码: 如何通过多线程实现? 2.分析 之所以采用多线程,是为了节省时间 3.解决方案 准备工作 logo文件 将生成的文件保存在F盘te ...
随机推荐
- 分布式处理与大数据平台(RabbitMQ&Celery&Hadoop&Spark&Storm&Elasticsearch)
热门的消息队列中间件RabbitMQ,分布式任务处理平台Celery,大数据分布式处理的三大重量级武器:Hadoop.Spark.Storm,以及新一代的数据采集和分析引擎Elasticsearch. ...
- Ionic APP 热更新 之 产品发布状态下的热更新搭建,去local-dev-addon插件
上一篇,我们介绍了在本地开发环境下的ionic项目热更新测试, 本文,我们将详细说明如何在去掉cordova-hot-code-push-local-dev-addon插件的情况下,实现热更新. 使用 ...
- 如何利用gulp构建前端自动化
1,使用 gulp.watch 来监听文件自动打包 在上篇文章中,介绍了如何利用webpack来为项目做打包编译等工作,其中介绍到在我们开发的时候,经常改动js,因为我们文件是引用编译后的js文件,若 ...
- 第一节:Java初识与计算机基础
一.计算机 = 硬件 + 软件 1.硬件:计算机中看的见摸得着的物理元件,例如:CPU(中央处理器).内存条.硬盘... CPU:计算机的运算和控制核心,主要用于对数据的逻辑运算以及对计算机指令的解析 ...
- Dijkstra Java
https://leetcode.com/problems/network-delay-time/ /* Java program to find a Pair which has maximum s ...
- 关于shader的学习
教程地址:https://onevcat.com/2013/07/shader-tutorial-1 因为想做一些特效,所以想稍微了解一下shader的代码,一下是一些笔记 // Upgrade NO ...
- Tips——canvas闪屏问题的处理
一.问题描述 在画canvas时,遇到屏幕瞬间空白的情况(大约1~2帧),造成用户体验不好. 二.原因 canvas的绘图过程是:先擦出整个画布:然后浏览器到达重绘时间点后,在空白的canvas上作画 ...
- java Date 当天时间戳处理
1. 代码 private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static Date ...
- axios上传图片(及vue上传图片到七牛))
浏览器上传图片到服务端,我用过两种方法: 1.本地图片转换成base64,然后通过普通的post请求发送到服务端. 操作简单,适合小图,以及如果想兼容低版本的ie没办法用此方法 2.通过form表单提 ...
- 正能量:You Are the Best
Success comes from knowing that you did your best to become the best that you are capable of becomin ...