当前位置:首页 » 编程语言 » python多线程queue

python多线程queue

发布时间: 2022-05-22 14:55:30

1. 在python多线程程序中引入queue模块可以解决什么问题

Queue模块提供了一个适用于多线程编程的先进先出数据结构,可以用来安全的传递多线程信息。 它本身就是线程安全的,使用put和get来处理数据,不会产生对一个数据同时读写的问题,所以是安全的。

2. python多线程怎样同步

锁机制
�6�9�6�9threading的Lock类,用该类的acquire函数进行加锁,用realease函数进行解锁

import threading
import time

class Num:
def __init__(self):
self.num = 0
self.lock = threading.Lock()
def add(self):
self.lock.acquire()#加锁,锁住相应的资源
self.num += 1
num = self.num
self.lock.release()#解锁,离开该资源
return num

n = Num()
class jdThread(threading.Thread):
def __init__(self,item):
threading.Thread.__init__(self)
self.item = item
def run(self):
time.sleep(2)
value = n.add()#将num加1,并输出原来的数据和+1之后的数据
print(self.item,value)

for item in range(5):
t = jdThread(item)
t.start()
t.join()#使线程一个一个执行
�6�9�6�9当一个线程调用锁的acquire()方法获得锁时,锁就进入“locked”状态。每次只有一个线程可以获得锁。如果此时另一个线程试图获得这个锁,该线程就会变为“blocked”状态,称为“同步阻塞”(参见多线程的基本概念)。
�6�9�6�9直到拥有锁的线程调用锁的release()方法释放锁之后,锁进入“unlocked”状态。线程调度程序从处于同步阻塞状态的线程中选择一个来获得锁,并使得该线程进入运行(running)状态。

信号量
�6�9�6�9信号量也提供acquire方法和release方法,每当调用acquire方法的时候,如果内部计数器大于0,则将其减1,如果内部计数器等于0,则会阻塞该线程,知道有线程调用了release方法将内部计数器更新到大于1位置。

import threading
import time
class Num:
def __init__(self):
self.num = 0
self.sem = threading.Semaphore(value = 3)
#允许最多三个线程同时访问资源

def add(self):
self.sem.acquire()#内部计数器减1
self.num += 1
num = self.num
self.sem.release()#内部计数器加1
return num

n = Num()
class jdThread(threading.Thread):
def __init__(self,item):
threading.Thread.__init__(self)
self.item = item
def run(self):
time.sleep(2)
value = n.add()
print(self.item,value)

for item in range(100):
t = jdThread(item)
t.start()
t.join()
条件判断
�6�9�6�9所谓条件变量,即这种机制是在满足了特定的条件后,线程才可以访问相关的数据。
�6�9�6�9它使用Condition类来完成,由于它也可以像锁机制那样用,所以它也有acquire方法和release方法,而且它还有wait,notify,notifyAll方法。

"""
一个简单的生产消费者模型,通过条件变量的控制产品数量的增减,调用一次生产者产品就是+1,调用一次消费者产品就会-1.
"""

"""
使用 Condition 类来完成,由于它也可以像锁机制那样用,所以它也有 acquire 方法和 release 方法,而且它还有
wait, notify, notifyAll 方法。
"""

import threading
import queue,time,random

class Goods:#产品类
def __init__(self):
self.count = 0
def add(self,num = 1):
self.count += num
def sub(self):
if self.count>=0:
self.count -= 1
def empty(self):
return self.count <= 0

class Procer(threading.Thread):#生产者类
def __init__(self,condition,goods,sleeptime = 1):#sleeptime=1
threading.Thread.__init__(self)
self.cond = condition
self.goods = goods
self.sleeptime = sleeptime
def run(self):
cond = self.cond
goods = self.goods
while True:
cond.acquire()#锁住资源
goods.add()
print("产品数量:",goods.count,"生产者线程")
cond.notifyAll()#唤醒所有等待的线程--》其实就是唤醒消费者进程
cond.release()#解锁资源
time.sleep(self.sleeptime)

class Consumer(threading.Thread):#消费者类
def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2
threading.Thread.__init__(self)
self.cond = condition
self.goods = goods
self.sleeptime = sleeptime
def run(self):
cond = self.cond
goods = self.goods
while True:
time.sleep(self.sleeptime)
cond.acquire()#锁住资源
while goods.empty():#如无产品则让线程等待
cond.wait()
goods.sub()
print("产品数量:",goods.count,"消费者线程")
cond.release()#解锁资源

g = Goods()
c = threading.Condition()

pro = Procer(c,g)
pro.start()

con = Consumer(c,g)
con.start()
同步队列
�6�9�6�9put方法和task_done方法,queue有一个未完成任务数量num,put依次num+1,task依次num-1.任务都完成时任务结束。

import threading
import queue
import time
import random

'''
1.创建一个 Queue.Queue() 的实例,然后使用数据对它进行填充。
2.将经过填充数据的实例传递给线程类,后者是通过继承 threading.Thread 的方式创建的。
3.每次从队列中取出一个项目,并使用该线程中的数据和 run 方法以执行相应的工作。
4.在完成这项工作之后,使用 queue.task_done() 函数向任务已经完成的队列发送一个信号。
5.对队列执行 join 操作,实际上意味着等到队列为空,再退出主程序。
'''

class jdThread(threading.Thread):
def __init__(self,index,queue):
threading.Thread.__init__(self)
self.index = index
self.queue = queue

def run(self):
while True:
time.sleep(1)
item = self.queue.get()
if item is None:
break
print("序号:",self.index,"任务",item,"完成")
self.queue.task_done()#task_done方法使得未完成的任务数量-1

q = queue.Queue(0)
'''
初始化函数接受一个数字来作为该队列的容量,如果传递的是
一个小于等于0的数,那么默认会认为该队列的容量是无限的.
'''
for i in range(2):
jdThread(i,q).start()#两个线程同时完成任务

for i in range(10):
q.put(i)#put方法使得未完成的任务数量+1

3. python 多线程

python支持多线程效果还不错,很多方面都用到了python 多线程的知识,我前段时间用python 多线程写了个处理生产者和消费者的问题,把代码贴出来给你看下:
#encoding=utf-8
import threading
import random
import time
from Queue import Queue

class Procer(threading.Thread):

def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue

def run(self):
for i in range(20):
print self.getName(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'

# Consumer thread

class Consumer(threading.Thread):

def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue

def run(self):

for i in range(20):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'

# Main thread

def main():

queue = Queue()
procer = Procer('Procer', queue)
consumer = Consumer('Consumer', queue)
print 'Starting threads ...'
procer.start()
consumer.start()
procer.join()
consumer.join()
print 'All threads have terminated.'
if __name__ == '__main__':
main()

如果你想要了解更多的python 多线程知识可以点下面的参考资料的地址,希望对有帮助!

4. Python多线程中队列到底是个什么概念

你首先需要创建一个线程池,其次将数据压进线程池,然后读取线程池。

import Queue
ThrQueue = Queue.Queue()
ThrQueue.put('数据')
ThrQueue.get()

当然以上步骤需要一个class来支撑,那说起来就多了!

5. python基于queue多线程怎么退出不了

添加数据很容易。Queue本身就是有锁的。建议在主线程(主程序中)添加,并处理其它线程的监督和处理结果的收集。 难的是取数据的线程。这个线程在取不到数据时,应该循环取,直到获取程序退出的通知。 使用threading里的Thread类。Queue通过初始...

6. 怎么样在python多线程实现检测服务器

需要ping一个网段所有机器的在线情况,shell脚步运行时间太长,用python写个多线程ping吧,代码如下:

#!/usr/bin/python
#coding=utf-8
'''
Created on 2015-8-4
@author: Administrator
'''

import threading,subprocess
from time import ctime,sleep,time
import Queue

queue=Queue.Queue()

class ThreadUrl(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue=queue

def run(self):
while True:
host=self.queue.get()
ret=subprocess.call('ping -c 1 -w 1 '+host,shell=True,stdout=open('/dev/null','w'))
if ret:
print "%s is down" % host
else:
print "%s is up" % host
self.queue.task_done()

def main():
for i in range(100):
t=ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in b:
queue.put(host)
queue.join()

a=[]
with open('ip.txt') as f:
for line in f.readlines():
a.append(line.split()[0])
#print a

b=['192.168.3.'+str(x) for x in range(1,254)] #ping 192.168.3 网段
start=time()
main()
print "Elasped Time:%s" % (time()-start)

#t2=threading.Thread(target=move,args=('fff',))
#threads.append(t2)

'''
for i in a:
print ctime()
ping(i)
sleep(1)

if __name__ == '__main__':
for t in range(len(a)):
#t.setDaemon(True)
threads[t].start()
#t.join()
print "All over %s" % ctime()
'''

7. Python multiprocessing.Queue 和 Queue有区别吗

觉得这个问题提的好,Queue是python自带的标准库,支持线程安全,所以多线程下可以随意使用,不会出现写冲突。multiprocessing.Queue这个multiprocessing模块封装的,它支持多进程之间的交互,比如master-worker模式下,master进程写入,work进程消费的模式,支持进程之间的通信。如果使用python做比较复杂的情况下,这个模块会经常用到

8. python3没有queue模块吗

有的,直接使用就可以了。
import queue
lr = queue.Queue()

9. Python multiprocessing.Queue() 和 Queue有区别吗

1.from Queue import Queue
这个是普通的队列模式,类似于普通列表,先进先出模式,get方法会阻塞请求,直到有数据get出来为止
2.from multiprocessing.Queue import Queue
这个是多进程并发的Queue队列,用于解决多进程间的通信问题。普通Queue实现不了。例如来跑多进程对一批IP列表进行运算,运算后的结果都存到Queue队列里面,这个就必须使用multiprocessing提供的Queue来实现

10. python 多queue有什么好处

死锁通常是因为你使用了锁。 在python里可以直接使用Queue,它自带了锁。你不需要自己设置一个锁。

所以严格来说,在python中,不需要锁。如果用到了锁,特别是多线程处理。要采用队列方式去解决,就没有这个问题了。

如果一定要用锁就存在死锁的情形。比如一个锁依赖另一个锁,在某种情形下,两者都打不开。特别是多线程的时候。

通常我们的办法是,在线程里设置一个心跳变量。在主线程里检查这个变量。如果一个线程长时间心跳停止 ,应该是死了。死锁也包括在内。

热点内容
优酷怎么给视频加密 发布:2025-05-14 19:31:34 浏览:633
梦三国2副本脚本 发布:2025-05-14 19:29:58 浏览:859
phpxmlhttp 发布:2025-05-14 19:29:58 浏览:432
Pua脚本 发布:2025-05-14 19:24:56 浏览:448
苹果像素低为什么比安卓好 发布:2025-05-14 19:13:23 浏览:460
安卓机微信怎么设置红包提醒 发布:2025-05-14 19:00:15 浏览:271
androidsystem权限设置 发布:2025-05-14 18:56:02 浏览:970
mq脚本 发布:2025-05-14 18:45:37 浏览:25
仙境传说ro解压失败 发布:2025-05-14 18:45:01 浏览:868
betweenand的用法sql 发布:2025-05-14 18:39:25 浏览:250