本文介绍了在此示例中是否需要使用线程锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个线程中将值附加到嵌套列表中,然后在主线程中复制具有列表理解功能的嵌套列表.我的示例中需要使用线程锁吗?我知道list.append()方法是线程安全的,但是在使用列表理解复制数据时是否需要使用锁?

I append values to a nested list in one thread, and I copy the growing nested list with list comprehension in the main thread. Do I need to use threading locks in my example? I know that the list.append() method is thread-safe, but would I need to use a lock when copying the data with list comprehension?

如果我确实需要使用锁,那么在copy_data()中而不是在GrowList._add_to_list()中使用锁是否有意义?

If I do need to use locks, would it make any sense to use a lock in copy_data() but not in GrowList._add_to_list()?

import threading
import time

class GrowList(object):
    def __init__(self):
        self.data = []
        self.stop_event = threading.Event()
        self.add_to_list()

    def _add_to_list(self):
        sample = [1, 2, 3, 4]
        while not self.stop_event.is_set():
            self.data.append(sample)
            time.sleep(1.0)

    def add_to_list(self):
        self.t = threading.Thread(target=self._add_to_list)
        self.t.start()

    def stop(self):
        self.stop_event.set()
        self.t.join()


def copy_data(nested_list):
    return [row[:] for row in nested_list]

推荐答案

认为您至少需要一个锁才能在一个线程中进行迭代同时添加另一个,而我认为不会不使用时复制数据时使用锁的感觉追加到列表时的锁.使用锁的要点是要在列表中声明某些所有权.

I think you need a lock at least for iterating in one threadwhile appending in the other, and I think it wouldn't makesense to use a lock when copying the data when you don't usea lock when appending to the list. The point of using a lockis to claim some ownership on the list.

您可能要问的另一个问题是:使用锁?您可以简单地保持代码清洁用self.data = MySafeList()替换self.data = []并通过分别编写一个带锁的小线程安全列表类.使用众多方法之一可以很容易地编写它@synchronized装饰器在这里和那里都可用.例如允许列表理解的__iter__方法可以是写为

Another question that you may ask is what is the point ofnot using a lock ? You could keep your code clean by simplyreplacing self.data = [] by self.data = MySafeList() andby writing separately a small thread safe list class with a lock.It could be written very easily by using one of the numerous@synchronized decorators available here and there. For examplethe __iter__ method that allows list comprehension could bewritten as

@synchronized
def __iter__(self):
    return iter(list(list.__iter__(self)))

这篇关于在此示例中是否需要使用线程锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:08
查看更多