以下三种情况,不知如何破,求大佬来解:
1、在类里面定义锁变量,self.lock,然后方法中使用。这种情况如果使用Process定义多进程,会有报错。
2、将锁变量传入方法。
3、不加锁,好像数据也没问题。
不知道上面3种情况,有没有正确的??
import random import time from multiprocessing import Process import threading class Test: def __init__(self): self.num = 0 # self.lock = threading.Lock() def thread_fun1(self, lock): for i in range(100): # 类内部定义锁变量 # self.lock.acquire() # try: # self.num += 1 # print(f'{threading.currentThread().name}, func1-{i}: {self.num}') # finally: # self.lock.release() # 外部传进来锁 # lock.acquire() # try: # self.num += 1 # print(f'{threading.currentThread().name}, func1-{i}: {self.num}') # finally: # lock.release() # 不加锁 self.num += 1 print(f'{threading.currentThread().name}, func1-{i}: {self.num}') # time.sleep(random.uniform(0.1, 1.0)) # time.sleep(1) def thread_fun2(self, lock): for i in range(100): # 类内部定义锁变量 # self.lock.acquire() # try: # self.num -= 1 # print(f'{threading.currentThread().name}, func2-{i}: {self.num}') # finally: # self.lock.release() # 外部传进来锁 # lock.acquire() # try: # self.num -= 1 # print(f'{threading.currentThread().name}, func2-{i}: {self.num}') # finally: # lock.release() # 不加锁 self.num -= 1 print(f'{threading.currentThread().name}, func2-{i}: {self.num}') # time.sleep(random.uniform(0.1, 1.0)) # time.sleep(1) def run(self): lock = threading.Lock() t_1 = threading.Thread(target=self.thread_fun1, args=(lock,)) t_2 = threading.Thread(target=self.thread_fun2, args=(lock,)) t_1.start() t_2.start() t_1.join() t_2.join() print(f'end num: {self.num}') def main(): proc = Process(target=Test().run) # 使用start,然后使用self.lock 会报错 # TypeError: can't pickle _thread.lock objects # 原因可能是lock不是一个可序列化的对象 # 然后改成把lock传入方法就不报错了 # 然后又试了下把锁去掉,数据好像也正确,不知道是不是量不够 proc.start() # 网上说把start改成run,又说run不是真的多进程,所以该不该用呢?? # proc.run() proc.join() if __name__ == '__main__': print('start main') main() print('end main')