Python线程锁

线程锁

当一个数据有多个线程都可以对其进行修改的时候,任何一个线程改变它都会对其他线程造成影响,如果我们某一个线程在使用完之前,其他线程不能对其修改,就需要对这个线程增加一个线程锁。

lock

lock注重的是局部,某一个变量没有调用完,其他线程不能调用。

import threading
import time
import random
count = 0
def get_money(money):
    global count
    count += money
    count += money
    count -= money
lock = threading.Lock()
def lock_thread(money):
    # 加锁
    lock.acquire()
    time.sleep(random.randint(1, 3))
    print('当前线程为',threading.current_thread().name)
    get_money(money)
    time.sleep(random.randint(1,3))
    print('当前线程为', threading.current_thread().name)
    # 解锁
    lock.release()
thread1 = threading.Thread(target=lock_thread,name='thread1',args=(10000,))
thread2 = threading.Thread(target=lock_thread,name='thread2',args=(15000,))
thread1.start()
thread2.start()
print('hello world')

输出结果为:

hello world
当前线程为 thread1
当前线程为 thread1
当前线程为 thread2
当前线程为 thread2

join

join注重的是整体,线程1没有执行完,线程2不能执行。

import threading
import time
import random
count = 0
def get_money(money):
    global count
    count += money
    count += money
    count -= money
def lock_thread(money):
    time.sleep(random.randint(1, 3))
    print('当前线程为',threading.current_thread().name)
    get_money(money)
    time.sleep(random.randint(1,3))
    print('当前线程为', threading.current_thread().name)
thread1 = threading.Thread(target=lock_thread,name='thread1',args=(10000,))
thread2 = threading.Thread(target=lock_thread,name='thread2',args=(15000,))
thread1.start()

thread1.join()

thread2.start()
print('hello world')

执行结果为:

当前线程为 thread1
当前线程为 thread1
hello world
当前线程为 thread2
当前线程为 thread2

猜你喜欢

转载自blog.csdn.net/qq_42543312/article/details/81410815