python爬虫-全局的资源访问问题
概述
为了解决全局的变量的问题,线程不同步。
线程锁的使用
代码1
#在使用多线程的情况下,会使用到全局变量
import threading
gmoney=0
lock=threading.Lock()
def creater():
global gmoney
lock.acquire()
for i in range(1000000):
gmoney+=1
lock.release()
print(gmoney)
return gmoney
def consumer():
global gmoney
lock.acquire()
for i in range(1000000):
gmoney+=1
print(gmoney)
lock.release()
return gmoney
if __name__ == '__main__':
threading.Thread(target=creater).start()
threading.Thread(target=consumer).start()
代码2:
import threading
import time
import random
money=0
lock=threading.Lock()
gtime=0
class Product(threading.Thread):
def run(self) -> None:
global money
global gtime
while True:
lock.acquire()
num=random.randint(<