前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python笔记:线程

python笔记:线程

作者头像
超级大猪
发布2019-11-22 09:44:37
3320
发布2019-11-22 09:44:37
举报
文章被收录于专栏:大猪的笔记大猪的笔记

1 简单用法

代码语言:javascript
复制
import threading 
i=0 
def foo():
    for i in range(10):
        i+=1
        print i  
 
t1 = threading.Thread(target=foo)
t2 = threading.Thread(target=foo) 
t1.start()
t2.start()

2 锁 #创建锁 mutex = threading.Lock() #锁定 mutex.acquire([timeout]) #释放 mutex.release() 3 event同步锁与线程类 event可以做为一个阻塞开关,阻塞时,如果另一边执行.set,就会释放阻塞。.clear函数可以恢复阻塞状态。

代码语言:javascript
复制
import threading
import time
import random
 
#使用event同步,依次打印线程名,若不加event锁,则为乱序
#两个线程依次循环:阻塞--> 等待对方释放自己 -->执行打印 -->恢复自己的阻塞 --> 释放对方
class Mythread1(threading.Thread):
    def __init__(self,myevent,otherevent):
        threading.Thread.__init__(self)
        self.threadEvent = myevent
        self.otherEvent = otherevent
        self.i=0
 
    def run(self):
       while(self.i<10):
            self.threadEvent.wait() #首先阻塞,等待另一边的线程释放这个锁
            time.sleep(random.randint(1,100)/70)
            self.i+=1
            print self.name,
            self.threadEvent.clear() #完成任务后,恢复event锁的可阻塞状态,让下个循环仍然会阻塞,等待释放
            self.otherEvent.set() #解锁另一个线程的阻塞,两个线程依次等待对方,依次执行,就能打印顺序的线程名
 
class Mythread2(threading.Thread):
    def __init__(self,myevent,otherevent):
        threading.Thread.__init__(self)
        self.threadEvent = myevent
        self.otherEvent = otherevent
        self.i=0
 
    def run(self):
        while(self.i<10):
            self.threadEvent.wait()
            time.sleep(random.randint(1,100)/70)
            self.i+=1
            print self.name,
            self.threadEvent.clear()
            self.otherEvent.set()
 
sinal1 = threading.Event()
sinal2 = threading.Event()
t1 = Mythread1(sinal1,sinal2)
t2 = Mythread2(sinal2,sinal1)
 
t1.start()
t2.start()
sinal1.set()
 
t1.join()
t2.join()

4 线程池 了解原理后,就能自己实现一个

代码语言:javascript
复制
import Queue
import threading
 
class ThreadPool(object):
    def __init__(self, work_num=1000,thread_num=2):
        self.work_queue = Queue.Queue(maxsize = work_num)
        self.threads = []
        self.__init_thread_pool(thread_num)
 
    def __init_thread_pool(self,thread_num):
        for i in range(thread_num):
            self.threads.append(Work(self.work_queue))
 
    def Add(self, func, *args):
        self.work_queue.put((func, list(args))) 
   
    def Wait(self):
        for item in self.threads:
            if item.isAlive():item.join()
 
    def Dispose(self):
        for item in self.threads:
            item.dispose=True
 
class Work(threading.Thread):
    def __init__(self, work_queue):
        threading.Thread.__init__(self)
        self.work_queue = work_queue
        self.dispose=False
        self.start()
 
    def run(self):
        while True:
            try:
                tempfunc, args = self.work_queue.get(timeout=5)
                tempfunc(*args)                
            except:
                if self.dispose==True:
                    break
                pass
调用
import threadpool
import threading
import time
 
def do_job(val1,val2):
    time.sleep(0.1)
    print val1,val2
 
pool = threadpool.ThreadPool() #new 一个线程池
 
for i in range(10):
    pool.Add(do_job,"hello",i) #添加十个任务到池中,它们一定会执行
 
time.sleep(1)
 
for i in range(10):
    pool.Add(do_job,"hello",i) #再添加十个任务到池中,它们一定会执行
 
t1 = threading.Thread(target=pool.Dispose()) #另起一个线程,发送dispose命令到线程池,在任务完成后线程池销毁
t1.start()
 
pool.Wait() #这个函数很有意思,等待线程池中的任务全部完成,一般系统级的线程池不会有这个函数

官方其实也提供了线程池,更简单稳定:

代码语言:javascript
复制
from multiprocessing.dummy import Pool as ThreadPool
import time
 
def loop():
    i = 0
    while True:
        i += 1
        # print("loop run", i)
        time.sleep(1)
 
def print_name():
    while True:
        strs = input("input:")
        print("print_name", strs)
 
p = ThreadPool(4)
p.apply_async(loop)
p.apply_async(print_name)
p.close()
p.join()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-05-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档