博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程2
阅读量:4481 次
发布时间:2019-06-08

本文共 7669 字,大约阅读时间需要 25 分钟。

一,守护线程

守护线程和守护进程是一样的,都是随着主进程或者主线程的结束而结束

from threading import Threadimport timedef func():    print('22')    time.sleep(1)    print('22')t=  Thread(target=func)t.setDaemon(True)t.start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py22Process finished with exit code 0

当我们再起一个线程时:

from threading import Threadimport timedef func():    print('11')    time.sleep(1)    print('22')t=  Thread(target=func)t.setDaemon(True)t.start()t1=  Thread(target=func)t1.start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py11112222Process finished with exit code 0

二,线程的锁

from threading import Threadfrom threading import Lockimport timedef func():    global n    time.sleep(1)    # l.acquire()    n-=1    # l.release()n=10l=Lock()l1=[]for i in range(10):    t=Thread(target=func)    t.start()    l1.append(t)[t.join() for t in l1]print(n)
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py0Process finished with exit code 0

有种特殊情况:

from threading import Threadfrom threading import Lockimport timedef func():    global n    time.sleep(1)    # l.acquire()    tt=n                  #从进程中获取值    time.sleep(1)    n=tt-1                 #再返回进程    # l.release()n=10l=Lock()l1=[]for i in range(10):    t=Thread(target=func)    t.start()    l1.append(t)[t.join() for t in l1]print(n)
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py9Process finished with exit code 0

这种情况还是要加锁的:

from threading import Threadfrom threading import Lockimport timedef func():    global n    time.sleep(1)    l.acquire()    tt=n    time.sleep(1)    n=tt-1    l.release()n=10l=Lock()l1=[]for i in range(10):    t=Thread(target=func)    t.start()    l1.append(t)[t.join() for t in l1]print(n)

GIL锁的不是数据,而是线程

 

三,死锁

from threading import RLockfrom threading import Threadfrom threading import Lockimport timea=Lock()b=Lock()def kill(name):    a.acquire()    print('%s拿到枪了'%name)    b.acquire()    print('%s拿到子弹了'%name)    print('%s杀人了' % name)    b.release()    a.release()def kill1(name):    b.acquire()    print('%s拿到子弹了' % name)    time.sleep(1)    a.acquire()    print('%s拿到枪了' % name)    print('%s杀人了' % name)    a.release()    b.release()Thread(target=kill,args=('二狗',)).start()Thread(target=kill1,args=('大狗',)).start()Thread(target=kill,args=('三狗',)).start()Thread(target=kill1,args=('四狗',)).start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py二狗拿到枪了二狗拿到子弹了二狗杀人了大狗拿到子弹了三狗拿到枪了

这就是死锁现象了,怎么解决这个问题呢?

from threading import RLockfrom threading import Threadfrom threading import Lockimport timeb=a=RLock()def kill(name):    a.acquire()    print('%s拿到枪了'%name)    b.acquire()    print('%s拿到子弹了'%name)    print('%s杀人了' % name)    b.release()    a.release()def kill1(name):    b.acquire()    print('%s拿到子弹了' % name)    time.sleep(1)    a.acquire()    print('%s拿到枪了' % name)    print('%s杀人了' % name)    a.release()    b.release()Thread(target=kill,args=('二狗',)).start()Thread(target=kill1,args=('大狗',)).start()Thread(target=kill,args=('三狗',)).start()Thread(target=kill1,args=('四狗',)).start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py二狗拿到枪了二狗拿到子弹了二狗杀人了大狗拿到子弹了大狗拿到枪了大狗杀人了三狗拿到枪了三狗拿到子弹了三狗杀人了四狗拿到子弹了四狗拿到枪了四狗杀人了Process finished with exit code 0

用RLock就可以解决这个问题了

lock是互斥锁

RLock是递归锁

 

四  信号量

from threading import Threadfrom threading import Semaphoreimport timeimport randomdef func(i,sem):    sem.acquire()    print('我是%s'%i)    time.sleep(random.random())    print('我是%s'%i)sem=Semaphore(5)for i in range(10):    Thread(target=func,args=(i,sem)).start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py我是0我是1我是2我是3我是4我是3我是4我是1我是2我是0

信号量和线程池的区别,信号量是一次就显示这些线程,而线程池是每次就开这么多线程

五,事件

from threading import Eventfrom threading import Threadfrom threading import Semaphoreimport timeimport randomdef func():    count = 1    while not e.is_set():  # 当事件的flag为False时才执行循环内的语句        if count > 3:            raise TimeoutError        print('尝试连接第%s次' % count)        count += 1        e.wait(0.5)  # 一直阻塞变成了只阻塞0.5    print('连接成功')  # 收到check_conn函数内的set指令,让flag变为True跳出while循环,执行本句代码def check_conn():    '''    检测数据库服务器的连接是否正常    '''    time.sleep(random.randint(1, 2))  # 模拟连接检测的时间    e.set()  # 告诉事件的标志数据库可以连接e = Event()check = Thread(target=check_conn)check.start()conn = Thread(target=func)conn.start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py尝试连接第1次尝试连接第2次连接成功Process finished with exit code 0

六,,条件

import threadingdef func(i):   t.acquire()   t.wait()   print('hello%s'%i)   t.release()if __name__=='__main__':    t=threading.Condition()#条件,锁加wait()功能    for i in range(10):        threading.Thread(target=func,args=(i,)).start()    while 1:        info=input('>>>')        if info=='q':            break        t.acquire()        if info=='all':            t.notify_all()        else:            t.notify(int(info))        t.release()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py>>>2>>>hello0hello1

根据你设定的条件,设定每次执行多少线程

七,定时器

from threading import  Timerdef func():    print('hello')Timer(4,func).start()
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.pyhelloProcess finished with exit code 0

八,队列

import queuet=queue.LifoQueue()t.put(1)t.put(2)t.put(3)print(t.get())C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py3Process finished with exit code 0

后进先出

import queuet=queue.PriorityQueue()t.put((1,'q'))t.put((4,'e'))t.put((3,'g'))t.put((3,'o'))print(t.get())print(t.get())print(t.get())print(t.get())
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py(1, 'q')(3, 'g')(3, 'o')(4, 'e')Process finished with exit code 0
# 值越小越优先,值相同就asc码小的先出

 

九,concurrent

 

import timeimport randomfrom concurrent import futuresdef func(n):    print(n)    time.sleep(random.randint(1,3))    return n*'*'def fu(c):    print(c.result())f=futures.ThreadPoolExecutor(3)#线程池f.submit(func,2)#submit=start
C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py2Process finished with exit code 0

 

 

返回值:

import timeimport randomfrom concurrent import futuresdef func(n):    print(n)    time.sleep(random.randint(1,3))    return n*'*'def fu(c):    print(c.result())f=futures.ThreadPoolExecutor(3)#线程池t=f.submit(func,2)#submit=startprint(t.result())#result打印返回值C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py2**Process finished with exit code 0

 

 

import timeimport randomfrom concurrent import futuresdef func(n):    print(n)    time.sleep(random.randint(1,3))    return n*'*'def fu(c):    print(c.result())f=futures.ThreadPoolExecutor(3)#线程池l=[]for i in range(10):    t=f.submit(func,i)#submit=start    l.append(t)f.shutdown()#相当于close()和join()集合体for i in l:    print(i.result())C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py0123456789*********************************************Process finished with exit code 0

 

 

 

 

回调:

import timeimport randomfrom concurrent import futuresdef func(n):    # print(n)    time.sleep(random.randint(1,3))    return n*'*'def fu(c):    print(c.result())f=futures.ThreadPoolExecutor(3)#线程池l=[]for i in range(10):#     t=f.submit(func,i)#submit=start#     l.append(t)# f.shutdown()#相当于close()和join()集合体# for i in l:#     print(i.result())    f.submit(func,i).add_done_callback(fu)#回调C:\Users\hc\AppData\Local\Programs\Python\Python36\python3.exe C:/s9/day39/39.py*********************************************Process finished with exit code 0

 

posted on
2018-02-07 22:27 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/xuguangzong/p/8428714.html

你可能感兴趣的文章
结构化方法与面向对象方法的比较
查看>>
简单的mongo小工具 python
查看>>
'Python.exe' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
查看>>
jquery easyui tab加载内容的几种方法
查看>>
mysql数据库优化步骤
查看>>
Sublime Text 3 常用插件 —— SFTP
查看>>
python 终极篇 --- django 路由系统
查看>>
IntelliJ IDEA平台下JNI编程(五)—本地C代码创建Java对象及引用
查看>>
Android jni 二维数组 传递
查看>>
Swift - whose view is not in the window hierarchy 问题解决方法
查看>>
说一说ASCLL和Unicode
查看>>
Swift - 几种使用数组的数据存储模型
查看>>
Swift - 使用UI Dynamics给UIKit组件添加移动吸附行为
查看>>
Android SwitchButton(滑动开关)
查看>>
多路复用I/O poll()
查看>>
Scalaz(0) - 写在前面
查看>>
poj 1731 Orders
查看>>
vs2010新建的cocos2d-x (XP操作系统) debug的时候报错
查看>>
JQuery学习---JQuery深入学习
查看>>
Java代码检测工具
查看>>