在对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)的更多相关文章

  1. C++实现多线程类Thread

    Windows编程中创建线程的常见函数有:CreateThread._beginthread._beginthreadex.据说在任何情况下_beginthreadex都是较好的选择. _begint ...

  2. “全栈2019”Java多线程第二章:创建多线程之继承Thread类

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  3. 【C#多线程】1.Thread类的使用及注意要点

    Thread随便讲讲 因为在C#中,Thread类在我们的新业务上并不常用了(因为创建一个新线程要比直接从线程池拿线程更加耗费资源),并且在.NET4.0后新增了Task类即Async与await关键 ...

  4. 多线程之继承Thread类及多线程内存分析

    *创建多线程的一种方式:继承Thread类 * java.lang.Thread是描述多线程的类,要实现多线程程序,一种方式就是继承Thread类 * 1.创建一个类Mythread让其extends ...

  5. java多线程系类:基础篇:02常用的实现多线程的两种方式

    本章,我们学习"常用的实现多线程的2种方式":Thread 和 Runnable.之所以说是常用的,是因为通过还可以通过java.util.concurrent包中的线程池来实现多 ...

  6. java多线程系类:基础篇:01基本概念:

    这个系类的内容全部来源于http://www.cnblogs.com/skywang12345/p/3479024.html.特别在此声明!!! 本来想直接看那位作家的博客的,但还是复制过来. 多线程 ...

  7. Java多线程——ThreadLocal类

    一.概述   ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是threadlocalvariable(线程局部变量).也许把它命名 ...

  8. c#通用多线程基类,以队列形式

    c#通用多线程基类,以队列形式 个人原创.欢迎转载.转载请注明出处.http://www.cnblogs.com/zetee/p/3487084.html 多线程这个概念大家都很熟悉,对于winfor ...

  9. Java多线程4:Thread中的静态方法

    一.Thread类中的静态方法 Thread类中的静态方法是通过Thread.方法名来调用的,那么问题来了,这个Thread指的是哪个Thread,是所在位置对应的那个Thread嘛?通过下面的例子可 ...

  10. java 如何使用多线程调用类的静态方法?

      1.情景展示 静态方法内部实现:将指定内容生成图片格式的二维码: 如何通过多线程实现? 2.分析 之所以采用多线程,是为了节省时间 3.解决方案 准备工作 logo文件 将生成的文件保存在F盘te ...

随机推荐

  1. 机器学习--集成学习(Ensemble Learning)

    一.集成学习法 在机器学习的有监督学习算法中,我们的目标是学习出一个稳定的且在各个方面表现都较好的模型,但实际情况往往不这么理想,有时我们只能得到多个有偏好的模型(弱监督模型,在某些方面表现的比较好) ...

  2. 使用redis的发布订阅模式实现消息队列

    配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://w ...

  3. Smali 语法文档

    可以选择保存成pdf格式,查询起来挺方便的 if v0==0 go cond_0 if-eqz v0, :cond_0   if v0!=0 go cond_0 if-nez v0, :cond_0 ...

  4. EXCEL导出工具类及调用

    一.Excel导出工具类代码 package com.qiyuan.util; import java.io.OutputStream; import java.io.UnsupportedEncod ...

  5. form表单select的选项值选择

    html: <form action=""> <p>选择城市</p> <p> <select name="" ...

  6. 资料汇总--java开发程序员必备技能

    1.  熟练使用Java语言进行面向对象程序设计(面向对象:继承.多态.抽象): 有良好的编程习惯(阿里开发手册  链接:http://pan.baidu.com/s/1dFEA6cT 密码:kqj4 ...

  7. s11d27 算法

    s11d27 算法 一.理论 1.1 时间复杂度和空间复杂度的理论: 1)空间复杂度: 是程序运行所以需要的额外消耗存储空间,一般的递归算法就要有o(n)的空间复杂度了, 简单说就是递归集算时通常是反 ...

  8. 能ping通外网dns但不能上网一例

    一个win7本本仅通过一个无线路由一个人上网,突然一天不能上网了,甚是奇怪,一看本地连接均是正常的.而且能ping通外网的dns,但无论如何就是打不开网页,表现为输入任何网址很迅速的显示该页无法显示, ...

  9. win10 uwp 商业游戏

    本文告诉大家去做一个商业游戏,游戏很简单,几乎没有什么技术 游戏的开始,需要添加框架库,于是引用我自己写的库. 首先是创建一个启动页面,这个页面是显示启动的. 在显示启动的时候,是需要加载游戏需要使用 ...

  10. HTTP2 帧基础知识以及Header、CONTINUATION、DATA帧相关资料:

    HTTP2于2015年2月28日正式通过IETF组织批准发布,正式定稿.有关它的内容可以参考:  HTTP2 概述  http://www.cnblogs.com/ghj1976/p/4552583. ...