首页 新闻 搜索 专区 学院

请教一个python的多线程问题

0
悬赏园豆:10 [待解决问题]

我直接把代码和需求放上来,很简短的,

麻烦大家帮我看下,如果要实现注释中的需求,代码该怎么改,

谢谢!

#需求:我想把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()
hexllo的主页 hexllo | 菜鸟二级 | 园豆:326
提问于:2021-02-18 16:17
< >
分享
所有回答(3)
0

我就想知道这个为什么还要用到多线程?

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)
事燃so释然 | 园豆:196 (初学一级) | 2021-02-19 09:25
0
#加入锁即可,因为懒锁就加载函数开始和函数结束,你这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()

小小咸鱼YwY | 园豆:3191 (老鸟四级) | 2021-02-19 09:48
0
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()
HPCM | 园豆:202 (菜鸟二级) | 2021-02-21 14:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册