python 多线程写法

继承线程类的方法方法

import threading
import queue
import time
workQueue = queue.Queue(maxsize=10)
lock=threading.Lock()

def detect_face(face_data,thread_name):
    for i in range(5):
        # time.sleep(1)
        print("线程(%s)___%s_%sdetect_face%s" %(thread_name,face_data,i,i))

def put_item(data, lock=lock):
    lock.acquire()
    workQueue.put(data)
    lock.release()

def get_item(thread_name,lock = lock):
    while True:
        print("从队列循环取数据")
        # time.sleep(2)
        if workQueue.empty():
            time.sleep(1)
            print("queue消息数量为%s" % workQueue.qsize())
        else:
            try:
                lock.acquire()
                item = workQueue.get(timeout=True)
                detect_face(item,thread_name)
            except Exception as e:
                continue
            finally:
                lock.release()
                time.sleep(1)

class Mythread(threading.Thread):
    def __init__(self, thread):
        threading.Thread.__init__(self)
        self.thread = thread
    def run(self,*args,**kwargs):
        print("调用了线程的run函数")
        print("Starting " + self.thread)
        get_item(self.thread)
        print ("Exiting " + self.thread)

def create_thread():
    threadList = ["Thread-1", "Thread-2", "Thread-3", "Thread-4", "Thread-5"]
    # 创建一个队列,设置队列的大小
    threads = []
    for _thread in threadList:
        thread = Mythread(_thread)
        thread.start()
        threads.append(thread)# 等待所有的线程都运行完
    for t in threads:
        t.join()

def main(data):
    put_item(data)
    print("插入数据完成,数据长度%s" % workQueue.qsize())
    create_thread()
# if __name__ == '__main__':
#     # import create_q
#     # create_q.inse()
#     put_item(data)

    # time.sleep(5)
    # print("创建多线程")
    # create_thread()
    # print("执行结束")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值