正确使用threading.RLock

时间:2017-11-14 00:24:21

标签: python multithreading

我正在Python中创建一个实用程序,它在一个单独的线程上从启动时的文件中读取数据,以便可以加载其余的GUI组件。数据存储在list中,然后附加到组合框中。如何锁定list,以便其他方法无法在def read_employees(self, read_file):方法使用的同时调用列表。

这是我能想到的最好的尝试。

#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吗?

1 个答案:

答案 0 :(得分:1)

我不知道你在应用中发生了什么,但我建议你看一下wx.CallAfter函数。它是线程安全的,可用于发送消息或发布事件。

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块,因为代码等同于:

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块。因为你只是:

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

有关并发期货和执行人的更多信息,see here for documention