python学习笔记之---多线程

#创建线程
#encoding=utf-8
from threading import Thread  #引入线程的包
import time
 
 
def run(a = None, b = None) :
  print(a, b )
  time.sleep(1)
 
 
t = Thread(name = "g1",target = run, args = ("g1", "thread"))
#此时线程是新建状态
 
 
print(t.getName()) #获得线程对象名称
print(t.isAlive()) #判断线程是否还活着,在start后,在执行完毕前调用isAlive()才会返回True
t.start() #启动线程
t.join()  #主线程等待子线程t执行结束
print("Done!")
D:\>py -3 a.py
g1
False
g1 thread
Done!
 
 
#通过继承Thread类创建线程
#encoding=utf-8
import threading  
import time  
class timer(threading.Thread):
    #The timer class is derived from the class threading.Thread
    def __init__(self, num, interval):  
        threading.Thread.__init__(self)  
        self.thread_num = num  
        self.interval = interval  
        self.thread_stop = False
 
 
    def run(self):
        #Overwrite run() method, put what you want the thread do here  
        while not self.thread_stop:  
            print('Thread Object(%d), Time:%s\n' %(self.thread_num, time.ctime())  )
            time.sleep(self.interval)
    def stop(self):  
        self.thread_stop = True  
 
 
def test():  
    thread1 = timer(1, 1)  
    thread2 = timer(2, 2)  
    thread1.start()  #执行类里面的run方法
    thread2.start()  
    time.sleep(10)  
    thread1.stop()  
    thread2.stop()  #停止线程
 
 
if __name__ == '__main__':  
    test()
D:\>py -3 a.py
Thread Object(1), Time:Fri Nov  8 22:35:12 2019
 
Thread Object(2), Time:Fri Nov  8 22:35:12 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:13 2019
 
Thread Object(2), Time:Fri Nov  8 22:35:14 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:14 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:15 2019
 
Thread Object(2), Time:Fri Nov  8 22:35:16 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:16 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:17 2019
 
Thread Object(2), Time:Fri Nov  8 22:35:18 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:18 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:19 2019
 
Thread Object(2), Time:Fri Nov  8 22:35:20 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:20 2019
 
Thread Object(1), Time:Fri Nov  8 22:35:21 2019
 
 
#守护线程
# encoding: UTF-8
import threading  
import time  
class MyThread(threading.Thread):  
  def __init__(self, id):  
    threading.Thread.__init__(self)  
 
  def run(self):  
    time.sleep(5)  
    print("This is " + self.getName())  
 
if __name__ == "__main__":  
  t1 = MyThread(999)  
  #t1.setDaemon(True) # 将子线程设置为守护线程
  t1.start()  
  print("I am the father thread.")
D:\>py -3 a.py
I am the father thread.
This is Thread-1
 
#线程池
#encoding=utf-8
import time
from multiprocessing.dummy import Pool as ThreadPool
#ThreadPool表示给线程池取一个别名ThreadPool
 
def run(fn):
  time.sleep(2)
  print(fn,end="")
 
if __name__ == '__main__':
  testFL = [1,2,3,4,5]
  pool = ThreadPool(10)#创建10个容量的线程池并发执行
  pool.map(run, testFL)
  pool.close()
  pool.join()
D:\>py -3 a.py
54321
 
 
线程锁
#encoding=utf-8
import time
from multiprocessing.dummy import Pool as ThreadPool
#ThreadPool表示给线程池取一个别名ThreadPool
 
def run(fn):
  time.sleep(2)
  print(fn,end="")
 
if __name__ == '__main__':
  testFL = [1,2,3,4,5]
  pool = ThreadPool(10)#创建10个容量的线程池并发执行
  pool.map(run, testFL)
  pool.close()
  pool.join()
 
 
#生产者和消费者
#encoding=utf-8
import threading
import time
 
 
data = 0
lock = threading.Lock()#创建一个锁对象
 
 
def func() :
  global data
  print("%s acquire lock...\n" %threading.currentThread().getName())
  if lock.acquire() :
    print("%s get lock...\n" %threading.currentThread().getName())
    data += 1 #must lock
    time.sleep(2)#其它操作
    print("%s release lock...\n" %threading.currentThread().getName())
 
 
    #调用release()将释放锁
    lock.release()
 
 
 
 
startTime = time.time()
t1 = threading.Thread(target = func)
t2 = threading.Thread(target = func)
t3 = threading.Thread(target = func)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
 
 
endTime = time.time()
print("used time is", endTime - startTime)
D:\>py -3 a.py
Thread-1 acquire lock...
 
Thread-2 acquire lock...
 
Thread-1 get lock...
Thread-3 acquire lock...
 
 
Thread-1 release lock...
 
Thread-2 get lock...
 
Thread-2 release lock...
 
Thread-3 get lock...
 
Thread-3 release lock...
 
used time is 6.0552496910095215
 
 
>>> q.empty()
True
>>> q.full()
False
>>> q.qsize
<bound method Queue.qsize of <queue.Queue object at 0x0000000002551470>>
>>> q.qsize()
0
>>> q.get_nowait()
 
 
#死锁
#coding=utf-8
import threading  
import time
 
 
lock1 = threading.Lock()  
lock2 = threading.Lock()  
print(lock1, lock2)
class T1(threading.Thread):  
    def __init__(self, name):  
        threading.Thread.__init__(self)  
        self.t_name = name  
 
 
    def run(self):  
        lock1.acquire()  
        time.sleep(1)#睡眠的目的是让线程2获得调度,得到第二把锁
        print('in thread T1',self.t_name)
        time.sleep(2)
        lock2.acquire() #线程1请求第二把锁
        print('in lock l2 of T1')  
        lock2.release()      
        lock1.release()
 
 
class T2(threading.Thread):  
    def __init__(self, name):  
        threading.Thread.__init__(self)  
        self.t_name = name  
 
 
    def run(self):  
        lock2.acquire()  
        time.sleep(2)#睡眠的目的是让线程1获得调度,得到第一把锁
        print('in thread T2',self.t_name)
        lock1.acquire() #线程2请求第一把锁
        print('in lock l1 of T2')
        lock1.release()
        lock2.release()
 
 
def test():  
    thread1 = T1('A')  
    thread2 = T2('B')  
    thread1.start()  
    thread2.start()  
 
 
if __name__== '__main__':  
    test()
D:\>py -3 a.py
<unlocked _thread.lock object at 0x0000023760EA8B98> <unlocked _thread.lock object at 0x0000023760EA8C38>
in thread T1 A
in thread T2 B
t2:拿到了lock2锁,等lock1锁
 
t1:拿到了lock1锁,等lock2锁
 
 
 
 
 

协程
协程:一个线程里的多个任务
#yield实现协程
import time
 
def consumer(name):    #生成器
    print("%s 要开始吃包子了!"%(name))
    while True:
        baozi=yield    #暂停,记录位置,返回跳出(接收下面send发送的数据,接收到数据后才会继续执行)
        print("包子%s,%s吃了"%(baozi,name))
 
 
def producer(name):
    c=consumer("消费者")    #只是变成一个生成器
    c.__next__()       #next只唤醒yield不传递值
    for i in range(4): #暂停
        time.sleep(1)
        print("%s 做了包子%s"%(name,i))
        c.send(i)      #发送数据
 
if __name__=="__main__":
    producer("生产者")
 
 
 
from greenlet import greenlet
 
def proc1():  #任务1
    print(12)
    gr2.switch()
    print(34)
    gr2.switch()
 
def proc2(): #任务2
    print(56)
    gr1.switch() #切换
    print(78)
 
if __name__=="__main__":
    gr1=greenlet(proc1)  #启动一个协程
    gr2=greenlet(proc2)
    gr1.switch()  #先执行gr1指定运行的函数,然后在切换到gr2

猜你喜欢

转载自www.cnblogs.com/wenm1128/p/11837305.html