简体   繁体   English

必要时使用线程和锁?

[英]Threads and locks when necessary?

Say I have an empty multidimensional list data = [[], []] and a function which appends values to one of the sublists:假设我有一个空的多维列表data = [[], []]和一个 function 将值附加到子列表之一:

def append(data):
   #appending values to data

I start two threads, each appending data to one of the respective sublists:我启动了两个线程,每个线程都将数据附加到各自的子列表之一:

t1 = threading.Thread(target = append, args = [data[0]])
t2 = threading.Thread(target = append, args = [data[1]])

Do I have to worry that this is going to mess things up?我必须担心这会搞砸事情吗? I'm new to threading and I read that you have to use locks because there can be a problem when threads try to access a variable at the same time.我是线程新手,我读到您必须使用锁,因为当线程尝试同时访问变量时可能会出现问题。 But I haven't see any problem with my code.但我没有看到我的代码有任何问题。 Is it okay in this case because the threads access different sub-arrays?在这种情况下是否可以,因为线程访问不同的子数组?

As you're using different lists, you won't have an issue at all.当您使用不同的列表时,您根本不会遇到问题。

In fact, if all you're doing is appending, and don't mind the order, you may even use the same list and append to it from different threads.事实上,如果您所做的只是追加,并且不介意顺序,您甚至可以从不同的线程使用相同的列表和 append 到它。

The default Python implementation, CPython, has a GIL (Global Interpreter Lock).默认的 Python 实现,CPython,有一个 GIL(全局解释器锁)。 Apart from memory management, the GIL makes sure single operations on pure mutable builtin primitives, such as dict, list and set, will cause no interference.除了 memory 管理之外,GIL 确保对纯可变内置原语(如 dict、list 和 set)的单个操作不会造成干扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM