python 多线程 限制线程数据_Python中多线程处理数据和实时显示、线程和锁设计...

有数据要显示给用户和功能来处理它们。每次用户与数据交互时,必须对所有数据运行函数,并将结果显示给用户。这应该是多线程的,这样当函数需要较长时间处理时就不会出现用户交互延迟。在

现在,我有两个线程共享List,第一个线程是以60fps的速度运行opengl循环,显示List的内容(而不仅仅是读取)。第二个是休眠,当用户与数据交互时,它会被唤醒,运行函数并通过赋值操作将结果写入List。如果用户在函数完成之前进行交互,第二个线程将中断函数并重新启动。实现如下:class RestartableThread(threading.Thread):

def __init__(self, input, output_list):

threading.Thread.__init__(self)

self.output = output_list

self.input = input

self._restart = threading.Event()

self._paused = threading.Event()

self._state = threading.Condition()

def restart(self, input):

with self._state:

self.input = input # get new input

self._restart.set()

self._paused.clear()

self._state.notify() # unblock self if in paused mode

def run(self):

while True:

with self._state:

if self._paused.is_set():

self._state.wait() # wait until notify() - the thread is paused

self._restart.clear()

self.function()

def function(self):

# start empty

result = []

for elem in self.input:

# end if restarted

if self._restart.is_set():

return

# do something with elem that takes time

result.append(elem)

# done

self.output = result

# enter sleep

with self._state:

self._paused.set() # enter sleep mode

return

除了第一个线程的opengl循环的fps很好地达到了60,但是当用户交互时,线程2的工作时间降到了20。是因为第二个线程与List一起工作,而线程1不能有效地从中读取数据吗?上面没有锁。我试过了。。在

^{pr2}$

…所以该函数只对列表的副本有效,但fps-drop行为相同。最好的实现方式是什么(可能是队列)?在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值