python中的线程和进程使用

线程基础

import threading  #线程库
import time
import queue

class myThread(threading.Thread): #继承线程库里面的Thread类
    def __init__(self,threadname,threadid,waittime):
        '''线程名,线程id,等待执行时间'''
        threading.Thread.__init__(self)  #必须要有这句  没有的话就报错
        self.threadName=threadname
        self.threadId=threadid
        self.wait=waittime

    # '''1.简单调用线程:无序的'''
    # def run(self) :
    #     '''线程执行start()函数时自动调用run函数'''
    #     print("Starting thread:"+self.threadName)
    #     print_time(self.name, self.wait, 5)
    #     print("Exit thread:"+self.threadName)

    '''2.线程同步方式,实现有序'''
    '''2.1:锁机制实现同步'''
    def run(self):
        print("Starting thread:" + self.threadName)
        threadLock.acquire() #获得锁,等这个线程跑完后再执行下一个线程
        print_time(self.threadName, self.wait, 5)
        print("Exit thread:" + self.threadName)
        threadLock.release()  #释放锁

def print_time(threadName, delay, counter):
   while counter:
      time.sleep(delay)
      print("%s process at: %s" % (threadName, time.ctime(time.time())))
      counter -= 1

'''1.简单调用线程:无序的'''
# thread1=myThread("one",1,1)
# thread2=myThread("two",2,2)
# thread1.start()
# thread2.start()
# thread1.join()  #
# thread2.join()
'''2.线程同步方式,实现有序'''
'''2.1:锁机制实现同步:Lock()'''
threadLock=threading.Lock()  #调用库方法
thread3=myThread("three",3,3)
thread4=myThread("four",4,4)
#保证队列方式一前一后进入
# thread3.start()
# thread3.join()  #这里是保证线程3先走完,然后在走线程4的start方法,不用的话两个线程会同时走start任务
# thread4.start()
# thread4.join()
#或者这样循环也可以的
# threads=[]
# threads.append(thread3)
# threads.append(thread4)
# for t in threads:
#     t.start()
#     t.join()



'''2.2:同步队列实现有序:queue库
里面有FIFO(先进先出)队列、LIFO(后进先出)队列和优先级队列几种,自动实现了锁语言,能够在多线程中使用,也能实现线程同步
'''
class OrderThread(threading.Thread):
    def __init__(self,threadid,threadname,queuename):
        '''线程id,线程名,队列名'''
        threading.Thread.__init__(self)
        self.name=threadname
        self.id=threadid
        self.qu=queuename

    def run(self):
        print("start thread:"+self.name)
        process_data(self.name, self.qu)
        print("exit thread:"+self.name)

def process_data(name,queue):
    if queue.empty(): #如果队列为空,返回True,反之False
        print("队列是清空状态")
    else:
        data=queue.get()  #获取的是放入队列中的数据
        print("%s processing 中,数据为:%s" % (name,data))
    time.sleep(1)
workqueue = queue.Queue(10)  # 创建容量为10的队列
id=1
otherlist=['send','look','modify']
for td in otherlist:
    workqueue.put(td)
    id=id+1
id=1
threadlist=['thone','thtwo','ththree','thfour','thfive']

for th in threadlist:
    thread=OrderThread(id,th,workqueue)  #这里的队列是空的
    thread.start()
    thread.join()  #等待线程完成
    id=id+1

线程和队列

from threading import Thread
import queue  #队列,用于线程间通信
import threading

def produce(inputqueue):
    '''生产者函数:将初始东西放入队列'''
    lists=[]
    for i in range(1,1001): #1-1000的循环
        url = "http://test/"
        url=url+str(i)
        #print(url)
        if url in lists:
            continue
        else:
            inputqueue.put(url)
            lists.append(url)

def consumer(inputqueue,outputqueue):
    '''消费者函数:将初始url处理'''
    url=inputqueue.get()  #获取并将元素弹出队列
    print(url)
    outputqueue.put(str(threading.current_thread().getName()))
    inputqueue.task_done() #告诉队列这个元素的相关任务已经执行完成

if __name__=="__main__":
    #inputQueue=queue.Queue(maxsize=10)#队列并设置大小为10
    inputQueue = queue.Queue()
    outputQueue=queue.Queue()
    #1.单线程执行生产者函数:跑时间很久
    #(inputQueue)

    #2.使用多线程执行生产者函数:速度快
    mythread=Thread(target=produce,args=(inputQueue,)) #将args的参数传递给target中执行的函数使用
    mythread.daemon = True  #值为true时,主线程退出了,创建的子线程也跟着退出
    mythread.start()

    print("inputQueue的初始大小为:"+str(inputQueue.qsize()))
    for i in range(0,1001):  #这里决定了线程的个数
        consThread=Thread(target=consumer,args=(inputQueue,outputQueue,)) #用for循环实现N个消费者线程
        consThread.daemon = True  # 值为true时,主线程退出了,创建的子线程也跟着退出
        consThread.start()
    inputQueue.join()

多进程

import multiprocessing  #多进程
queue=multiprocessing.Manager().Queue() #进程队列
for i in range(0,1000):
    queue.put("http://testwas/"+str(i)) #放入进程队列
print("进程池大小:"+queue.qsize())

def consumer(inputqueue):
    '''消费者函数:将初始url处理'''
    url=inputqueue.get()  #获取并将元素弹出队列
    print(url)
    inputqueue.task_done() #告诉队列这个元素的相关任务已经执行完成,只有所有任务都task_done(),join函数才取消阻塞

pool=multiprocessing.Pool(10) #设置进程池大小为10
for index in range(1000):
    pool.apply_async(consumer,args=(queue))  #由于que的大小是1000,而pool进程池是限制了10,所以分批次每次执行10个进程,直到所有进程执行完成
pool.close()
pool.join()
queue.join()#队列消费完成才结束线程

更多案例参考:https://blog.youkuaiyun.com/weixin_40976261/article/details/89854114?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-0&spm=1001.2101.3001.4242

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值