我直接把代码和需求放上来,很简短的,
麻烦大家帮我看下,如果要实现注释中的需求,代码该怎么改,
谢谢!
#需求:我想把arr中的数字分别放在setA,setB中,A和B中的数字在多线程执行完后也不能相同 import random import threading class A: setA = set() setB = set() arr = [1, 2, 3, 4, 5,6,7,8,9,0] threads = [] def fun(self, condition): with condition: condition.wait() for i in self.arr: r = random.randrange(1, 100) if (r % 2 == 0): self.setA.add(i) elif(not i in self.setA): self.setB.add(i) condition.notify() def tFun(self): condition = threading.Condition() for i in range(10): t = threading.Thread(target=self.fun, args=(condition,)) self.threads.append(t) t.start() for t in self.threads: t.join() print(self.setA) print(self.setB) a = A() a.tFun()
我就想知道这个为什么还要用到多线程?
setA = set()
setB = set()
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
for i in arr:
r = random.randrange(0, 2)
if (r == 0):
setA.add(i)
else:
setB.add(i)
print(setA)
print(setB)
#加入锁即可,因为懒锁就加载函数开始和函数结束,你这Condition()本身你ctrl+左键看看他源码只不过导入了个锁的概念
import random
import threading
from multiprocessing import Lock
import queue
lock = queue
class A:
setA = set()
setB = set()
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
threads = []
def fun(self, lock):
lock.acquire()
for i in self.arr:
if (not i in self.setA):
self.setA.add(i)
else:
self.setB.add(i)
lock.release()
def tFun(self):
for i in range(10):
lock = Lock()
t = threading.Thread(target=self.fun, args=(lock,))
self.threads.append(t)
t.start()
for t in self.threads:
t.join()
print(self.setA)
print(self.setB)
a = A()
a.tFun()
import random
import threading
class A:
setA = set()
setB = set()
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
threads = []
def fun(self, condition):
with condition:
for i in self.arr:
r = random.randrange(1, 100)
if r % 2 == 0 and i not in self.setB:
self.setA.add(i)
elif i not in self.setA:
self.setB.add(i)
def tFun(self):
condition = threading.Condition()
for i in range(10):
t = threading.Thread(target=self.fun, args=(condition,))
self.threads.append(t)
t.start()
for t in self.threads:
t.join()
print(self.setA)
print(self.setB)
a = A()
a.tFun()