1 Star 0 Fork 0

mr_nobody/py_crawler

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
queue_test.py 3.02 KB
一键复制 编辑 原始数据 按行查看 历史
mr_nobody 提交于 2017-04-05 17:40 . threading on press
#!/usr/bin/python3
# coding: utf-8
"""
__title__ = ""
__author__ = "Hans"
__mtime__ = "2017/4/5 0005"
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
import random, threading, time
from queue import Queue
# producer thread
class Producer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
for i in range(10): # 随机产生10个数字, 可以修改为任意大小
randomnum = random.randint(1, 99)
print('{}:{} is producing {} to the queue'.format(time.ctime(), self.getName(), randomnum))
self.data.put(randomnum) # 将数据依次存入队列
time.sleep(1)
print('{}:{} is finished!'.format(time.ctime(), self.getName()))
# Consumer thread
class Consumer_even(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
while 1:
try:
val_even = self.data.get(1, 5) # get(self, block=True, timeout=None) 1是阻塞等待, 5 是超时5秒
if val_even % 2 == 0:
print('{}:{} is consuming, {} in the queue is consumed'.format(time.ctime(), self.getName(), val_even))
time.sleep(2)
else:
self.data.put(val_even)
time.sleep(2)
except: # 等待输入, 超过5秒, 就报异常
print('{}:{} finished'.format(time.ctime(), self.getName()))
break
class Consumer_odd(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
while 1:
try:
val_odd = self.data.get(1, 5) # get(self, block=True, timeout=None) 1是阻塞等待, 5 是超时5秒
if val_odd % 2 != 0:
print('{}:{} is consuming, {} in the queue is consumed'.format(time.ctime(), self.getName(), val_odd))
time.sleep(2)
else:
self.data.put(val_odd)
time.sleep(2)
except: # 等待输入, 超过5秒, 就报异常
print('{}:{} finished'.format(time.ctime(), self.getName()))
break
# main thread
def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer_even = Consumer_even('Con_even.', queue)
consumer_odd = Consumer_odd('Con_odd', queue)
producer.start()
consumer_even.start()
consumer_odd.start()
producer.join()
consumer_even.join()
consumer_odd.join()
print('All threads terminate!')
if __name__ == "__main__":
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/mr_nobody/py_crawler.git
[email protected]:mr_nobody/py_crawler.git
mr_nobody
py_crawler
py_crawler
master

搜索帮助