python多线程及互斥锁使用

def RunThread(target, *args): #传入一个函数多线程执行
    print u"启动线程:", target.__name__
    t = threading.Thread(target = target, args = args)
    #t.setDaemon(True) #设置为守护线程 当主进程结束后所有子线程都会结束
    t.start()

def fun1(): #每3秒输出一次fun1 总共输出5次
    for i in range(5):
        print "fun1"
        time.sleep(3)

def fun2(count, sleep): #每sleep输出一次fun2 总共输出count次
    for i in range(count):
        print "fun2"
        time.sleep(sleep)
        
RunThread(fun1) #创建一个线程运行fun1函数
RunThread(fun2, 5, 1) #创建一个线程运行fun2函数并给fun2函数传参5和1
print "end!"
'''
输出
启动线程: fun1
fun1启动线程:
 fun2
fun2end!

fun2
fun2
fun1
fun2
fun2
fun1
fun1
fun1
'''

使用threading模块创建多线程

x = 0
def fun1():
    global x
    for i in range(1000):
        x = x + 1

def fun2():
    global  x
    for i in range(1000):
        x = x + 1

t = threading.Thread(target = fun1)
t.start()
t = threading.Thread(target = fun2)
t.start()
time.sleep(3) #3秒足够让两个线程运行完毕
print x
#输出1603 和预计不符

多线程修改同一个全局变量出现问题

lock = threading.Lock()
x = 0
def fun1():
    global lock, x
    for i in range(1000):
        lock.acquire() #加锁
        x = x + 1
        lock.release() #解锁

def fun2():
    global lock, x
    for i in range(1000):
        lock.acquire()
        x = x + 1
        lock.release()

t = threading.Thread(target = fun1)
t.start()
t = threading.Thread(target = fun2)
t.start()
time.sleep(3) #3秒足够让两个线程运行完毕
print x
#使用互斥锁 输出正确结果2000

使用互斥锁保证数据正确

lock = threading.Lock()
def RunThread(target, *args): #传入一个函数多线程执行
    print u"启动线程:", target.__name__
    t = threading.Thread(target = target, args = args)
    #t.setDaemon(True) #设置为守护线程 当主进程结束后所有子线程都会结束
    t.start()

def fun():
    global lock
    lock.acquire()
    print "lock"
    time.sleep(2)
    lock.release()
    print "unlock"

RunThread(fun)
RunThread(fun)
for i in range(5):
    time.sleep(1)
    print "" #输出换行
'''
输出
启动线程: fun
启动线程:lock
fun

nlocklock



nlock


'''

当线程使用acquire尝试锁定lock时发现已经被锁定则进入阻塞状态 等待lock的解锁再继续运行

lock = threading.Lock()
x = 0
def fun1():
    global lock, x
    for i in range(1000):
        with lock: #执行with下指令自动加锁执行完毕自动解锁
            x = x + 1

def fun2():
    global lock, x
    for i in range(1000):
        with lock:
            x = x + 1

t = threading.Thread(target = fun1)
t.start()
t = threading.Thread(target = fun2)
t.start()
time.sleep(3) #3秒足够让两个线程运行完毕
print x

with 更加方便的加锁解锁

你可能感兴趣的:(python)