问题描述
我正在用Python创建一个实用程序,该实用程序在启动时会在单独线程上从文件中读取数据,以便可以加载其余的GUI组件.数据被存储到list
中,然后附加到组合框.我将如何锁定list
,以便其他任何方法都无法在def read_employees(self, read_file):
方法正在使用列表的同时调用该列表.
I'm creating a utility in Python that reads data in from a file on startup on a separate thread so that the rest of the GUI components can load. The data gets stored into a list
and then appended to a combobox. How would I lock the list
so that no other method can call the list at the same time it's being used by the def read_employees(self, read_file):
method.
这是我能想到的最好的尝试.
This is the best attempt I can come up with.
#left out imports
class MyDialog(wx.Frame):
def __init__(self, parent, title):
self.no_resize = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
wx.Frame.__init__(self, parent, title=title, size=(500, 450),style = self.no_resize)
self.lock = threading.RLock()
self.empList = []
def read_employees(self, read_file):
with open(read_file) as f_obj:
employees = json.load(f_obj)
with self.lock:
self.empList = [empEmail for empEmail in employees.keys()]
wx.CallAfter(self.emp_selection.Append, self.empList)
def start_read_thread(self):
filename = 'employee.json'
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
executor.submit(self.read_employees, filename)
app = wx.App(False)
frame = MyDialog(None, "Crystal Rose")
app.MainLoop()
在这里使用RLock
是否合适?
推荐答案
我不知道您在应用程序中还有什么其他工作,但是我建议您看一下wx.CallAfter函数.它是线程安全的,可用于发送消息或发布事件.
I don't know what else you have going on in the app, but I'd recommend taking a look at the wx.CallAfter function. It is thread-safe and can be used to send messages or post events.
import wx
from wx.lib.pubsub import Publisher
import json
from threading import Thread
def update_employee_list(read_file):
with open(read_file) as f_obj:
employee_list = json.load(f_obj) # this line should release the GIL so it continues other threads
# next line sends a thread-safe message to the main event thread
wx.CallAfter(Publisher().sendMesage, 'updateEmployeeList', employee_list)
class MyDialog(wx.Frame):
def __init__(self, parent, title):
self.no_resize = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
wx.Frame.__init__(self, parent, title=title, size=(500, 450),style = self.no_resize)
self.empList = []
# subscribe our function to be called when 'updateEmployeeList' messages are received
Publisher().subscribe(self.updateDisplay, 'updateEmployeeList')
def updateDisplay(self, employee_list):
# this assignment should be atomic and thread-safe
self.empList = employee_list
# wxPython GUI runs in a single thread, so this is a blocking call
# if you have many many list items, you may want to modify this method
# to add one employee at a time to the list to keep it non-blocking.
self.emp_selection.Append(employee_list)
def start_read_thread(self):
filename = 'employee.json'
t = Thread(target= update_employee_list, args=(filename, ))
t.start() # this starts the thread and immediately continues this thread's execution
更新:
使用with ThreadPoolExecutor
块是因为代码等效于:
Using a with ThreadPoolExecutor
blocks because the code is equivalent to:
executor = ThreadPoolExecutor(max_workers=1)
executor.submit(worker_func, args)
executor.shutdown(wait=True) # <--- wait=True causes Executor to block until all threads complete
您仍然可以按以下方式使用ThreadPoolExecutor,而无需使用with块.因为你只是:
You could still use the ThreadPoolExecutor as follows, without the with block. Because you're only :
executor = ThreadPoolExecutor(max_workers=1)
executor.submit(worker_func, args)
executor.shutdown(wait=False) # <--- threads will still complete, but execution of this thread continues immediately
有关并发期货和执行人的更多信息,请查看此处的记录文件.
For more about concurrent futures and Executors, see here for documention.
这篇关于正确使用threading.RLock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!