PY多线程打印列表

from queue import Queue
import threading
import time


class Test(object):
    def __init__(self,num):
        self.q =Queue()
        self.thread=num
        self.main()
    def double(self):
        for i in mylist:
            m=i*2
            self.q.put(m)
    def process(self,arg):
        while not self.q.empty():
            num=self.q.get()
            print (num,'.....','made by ',threading.currentThread().name)
            time.sleep(1)
    def main(self):
        self.double()
        threads=[]
        for i in range(self.thread):
            t=threading.Thread(target=self.process,args=[i,])
            threads.append(t)
            t.start()
        for t in threads:
            t.join()
        print('Thread over')
        # print ("Exiting Main Thread")


if __name__ == '__main__':
    mylist=set(x for x in range (101))
    exam=Test(10)



很早之前写的,最近在学多线进程。

我的自线程在哪里执行?进行process函数的时候打印了自线程的名字,其他时候都是mainthread执行。

网上说py的多线程鸡肋,一个Python进程中,只允许有一个线程处于运行状态,对于io密集型数据,用多线程是能够提高效率的。我想想这个简单的模块套到我那个弱智爬虫上面应该ok。

这里我把要处理的数据扔到了队列里。我想再了解下互斥锁。

from queue import Queue
import threading
import time


class Test(object):
    def __init__(self,num):
        self.q =Queue()#这里的参数似乎是定义了队列的大小
        self.thread=num
        self.main()
    def double(self):
        for i in mylist:
            m=i*2
            self.q.put(m)
    def process(self,arg):
        global mutex
        while not self.q.empty():
            if mutex.acquire():
                num=self.q.get()
                print (num,'.....','made by ',threading.currentThread().name)
                mutex.release()
            time.sleep(1)
    def main(self):
        self.double()
        threads=[]
        for i in range(self.thread):
            t=threading.Thread(target=self.process,args=[i,])
            threads.append(t)
            t.start()
            # t.join()这也会阻塞其他子线程
        for t in threads:
            t.join()
        print('Thread over')
        # print ("Exiting Main Thread")


if __name__ == '__main__':
    mutex=threading.Lock()
    mylist=set(x for x in range (101))
    exam=Test(10)
    print(threading.currentThread().name) 

参考 

互斥锁会降低效率,但我这里不明显(当然本身就是个小程序没什么意思)。保护数据吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值