import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num+1
msg = self.name+' set num to '+str(num)
print msg
mutex.acquire()
mutex.release()
mutex.release()
num = 0
mutex = threading.Lock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()
import threading
import time
class MyThread(threading.Thread):
def do1(self):
global resA, resB
if mutexA.acquire():
msg = self.name+' got resA'
print msg
if mutexB.acquire(1):
msg = self.name+' got resB'
print msg
mutexB.release()
mutexA.release()
def do2(self):
global resA, resB
if mutexB.acquire():
msg = self.name+' got resB'
print msg
if mutexA.acquire(1):
msg = self.name+' got resA'
print msg
mutexA.release()
mutexB.release()
def run(self):
self.do1()
self.do2()
resA = 0
resB = 0
mutexA = threading.Lock()
mutexB = threading.Lock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num+1
msg = self.name+' set num to '+str(num)
print msg
mutex.acquire()
mutex.release()
mutex.release()
num = 0
mutex = threading.RLock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()
lock = threading.Lock() lock.acquire() dosomething…… lock.release()
[root@361way lock]# cat lock1.py
#!/usr/bin/env python
# coding=utf-8
import threading # 导入threading模块
import time # 导入time模块
class mythread(threading.Thread): # 通过继承创建类
def __init__(self,threadname): # 初始化方法
# 调用父类的初始化方法
threading.Thread.__init__(self,name = threadname)
def run(self): # 重载run方法
global x # 使用global表明x为全局变量
for i in range(3):
x = x + 1
time.sleep(5) # 调用sleep函数,让线程休眠5秒
print x
tl = [] # 定义列表
for i in range(10):
t = mythread(str(i)) # 类实例化
tl.append(t) # 将类对象添加到列表中
x=0 # 将x赋值为0
for i in tl:
i.start()
[root@361way lock]# python lock1.py
30 30 30 30 30 30 30 30 30 30
[root@361way lock]# cat lock2.py
#!/usr/bin/env python
# coding=utf-8
import threading # 导入threading模块
import time # 导入time模块
class mythread(threading.Thread): # 通过继承创建类
def __init__(self,threadname): # 初始化方法
threading.Thread.__init__(self,name = threadname)
def run(self): # 重载run方法
global x # 使用global表明x为全局变量
lock.acquire() # 调用lock的acquire方法
for i in range(3):
x = x + 1
time.sleep(5) # 调用sleep函数,让线程休眠5秒
print x
lock.release() # 调用lock的release方法
lock = threading.Lock() # 类实例化
tl = [] # 定义列表
for i in range(10):
t = mythread(str(i)) # 类实例化
tl.append(t) # 将类对象添加到列表中
x=0 # 将x赋值为0
for i in tl:
i.start() # 依次运行线程
[root@361way lock]# python lock2.py
3 6 9 12 15 18 21 24 27 30
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有