threading包的例子和queue包的例子

参考:https://www.cnblogs.com/tkqasn/p/5700281.html

参考:https://www.cnblogs.com/tkqasn/p/5700281.html

threading用于提供线程相关的操作,线程是程序工作中最小的单元,python当前版本的多线程库中没有实现优先级、线程组、线程也不能被停止、暂停、恢复、中断。

threading中提供的类包括Thread、Lock、RLock、Condition、Event、Timer等

threading模块提供的常用方法包括:

threading.currentThread():返回当前的线程变量

threading.enumerate():返回一个包含当前正在运行的线程的list

threading.activeCount():返回正在运行的线程数量,与len(threading.enumerate())的效果相同

threading模块提供的常量:

threading.TIMEOUT_MAX:设置threading全局超时时间

简易的开启线程:

def sayhi(k):
    print('your id is %s' %k)  
t=threading.Thread(target=sayhi,args=('hh',))     #第一个参数target是线程函数变量,第二个参数args是一个数组变量参数如果只传递一个值就只需要一个i,如果要传递多个参数,那么还可以继续传递其他参数,其中逗号不能少,少了则不是数组。
t.start()
#type((1,))的返回结果为数组tuple

创建线程的两种方法:

import threading
import time
#方法一:将要执行的方法作为参数传给Thread的构造方法
def action(arg):
    time.sleep(1)
    print ('the arg is:%s\r' %arg)   #\r表示指针回到该行开头
for i in range(4):
    t =threading.Thread(target=action,args=(i,))   #开启线程,target表示要执行的方法,name表示线程名,args/kwargs表示要传入方法的参数
 t.start() print ('main thread end!') # 或者先建Thread的一个继承类,然后用这个类中的start()方法打开: t=threading.Thread(target=action,args=('hh',)) t.start() #方法二:从Thread继承,并重写run() class MyThread(threading.Thread): def __init__(self,arg): super(MyThread, self).__init__()#注意:一定要显式的调用父类的初始化函数。 self.arg=arg def run(self):#定义每个线程要运行的函数 time.sleep(1) print ('the arg is:%s\r' % self.arg) for i in range(4): t =MyThread(i) t.start() print ('main thread end!')

 简单的线程实例:

import threading  
import queue  
import time  
class mn_access(threading.Thread):  
 def __init__(self,interval):  
  threading.Thread.__init__(self) self.interval=interval self.thread_stop=False def run(self): #这个函数中存放用户自己的功能代码  i=1; while not self.thread_stop: print("thread%d %s: i am alive hehe %d" %(self.ident,self.name,i))  #name用于存放线程的名字,ident用于存放线程的标识 time.sleep(self.interval) i=i+1 def stop(self): self.thread_stop = True if __name__ == "__main__": mn=mn_access(1) mn.start() #线程开始 time.sleep(5) mn.stop()

 queue包的例子:

class workder(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue=queue
        self.thread_stop=False
    def run(self):
        while not self.thread_stop:
            print('thread %d %s :waiting for tast' %(self.ident,self.name))
            try:
                task=q.get(block=True,timeout=20)           #接收消息
            except queue.Empty:
                print('nothing to do! i will go home')
                self.thread_stop=True
                break
            print('task recv:%s,task no %d ' %(task[0],task[1]))
            print('i am working')
            time.sleep(3)
            print('work finished')
            q.task_done()             #完成一个任务
            res=q.qsize()             #判断队列的大小
            if res>0:
                print('fuck there are still %d task to do '%res)
    def stop(self):
        self.thread_stop=True
if __name__=='__main__':
    q=queue.Queue(3)
    worker=workder(q)
    worker.start()
    q.put(['produce one cup',1],block=True,timeout=None)           #产生任务消息
    q.put(['produce one desk',2],block=True,timeout=None)
    q.put(['produce one apple',3],block=True,timeout=None)
    q.put(['produce one banana',4],block=True,timeout=None)
    q.put(['produce one bag',5],block=True,timeout=None)
    print('********wait for finish')
    q.join()           #等待所有任务完成
    print('all task finished')

 

转载于:https://www.cnblogs.com/xiaochouk/p/8723738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值