多线程的运用 锁

例码

import threading
import time
import random

def reading():
    for i in range(5):
        print("线程reading",i)
        time.sleep(random.randint(1,2))
def writing():
    for i in range(5):
        print("线程writing",i)
        time.sleep(random.randint(1,2))

print("开始住线程")
r=threading.Thread(target=reading)  #运用函数为线程r
w=threading.Thread(target=writing)
r.start()                           #启动r线程
w.start()
w.join()							#等待w线程结束才继续下一步
# r.join()
print("the end")

线程资源管理

  1. 创建一个线程锁对象:lock=threading.RLock()
  2. lock对象有两种使用的方法acquire()和release()。
    lock.acquire()强行lock获取线程锁,到有线程先调用acquire()方法未调用release()释放锁,那么这个lock.acquire()就阻塞当前线程,直到别处release()。锁的控制权获得解除阻塞,线程继续执行。执行完成后使用lock.release()不然别线程无法调用。
import threading
import time
import random
lock=threading._RLock( )   # 实例lock类
words=["a","b","c","d","e","f"]

def increase():
    global words
    for count in range(5):
        lock.acquire( )  #
        print("A acquire")
        for i in range(len(words)):
            for j in range(i+1,len(words)):
                if words[i]>words[j]:
                    t=words[i]
                    words[j]=words[i]
                    words[j]=t
        print("A",words)
        time.sleep(1)
        lock.release( )
def decrease():
    global words
    for count in range(5):
        lock.acquire( )
        print ( "D acquire" )
        for i in range(len(words)):
            for j in range(i+1,len(words)):
                if words[i]<words[j]:
                    t=words[i]
                    words[i]=words[j]
                    words[j]=t
        print("D",words)
        time.sleep(1)
        lock.release( )
print("开始住线程")
a=threading.Thread(target=increase)
d=threading.Thread(target=decrease)
a.setDaemon(False)  #子线程在后台运行
a.start()
a.join()
d.setDaemon(False)
d.start()
print("the end")
'''
结果
C:\Users\lxq\AppData\Local\Programs\Python\Python37\pythonw.exe E:/python/test/xm/xm/web/threadingcode.py
开始住线程
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
the end
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
'''

知识点

  1. r=threading.Thread(target=reading) #运用函数为线程r
  2. r.start() #启动r线程
  3. w.join() #等待w线程结束才继续下一步
  4. lock=threading._RLock( ) #实例lock类
  5. lock.acquire( ) #获取锁
  6. lock.release()#释放锁
  7. a.setDaemon(False) #子线程a在后台运行(主线程结束依然进行) Turn在前台运行(主程序结束子程序也结束)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值