2

Please bear with me on this as I'm new to this.

I have an array and two threads.

First thread appends new elements to the array when required

myArray ~= newArray;

Second thread removes elements from the array when required:

extractedArray = myArray[0..10];
myArray = myArray[10..myArray.length()];

Is this thread safe? What happens when the two threads interact on the array at the exact same time?

4

3 回答 3

4

不,它不是线程安全的。如果您跨线程共享数据,那么您需要通过诸如同步语句同步函数互斥锁core.atomic等工具自己处理使其成为线程安全的。

但是,需要指出的另一件主要事情是 D 中的所有数据默认情况下都是线程本地的。因此,除非明确共享,否则您无法跨线程访问数据。因此,您通常根本不必担心线程安全。只有当您明确共享数据时,它才是一个问题。

于 2012-04-12T20:39:31.887 回答
2

这不是线程安全的

这有经典的丢失更新竞赛:

附加意味着检查数组以查看它是否可以就地扩展,如果不能,则需要在副本忙时进行(O(n)时间)副本,其他线程可以切片,当复制完成时件将返回

您应该考虑使用更容易使线程安全的链表实现

Java使用此处描述ConcurrentLinkedQueue的列表来实现它,您可以使用标准库中的core.atomic.cas()

于 2012-04-12T11:23:49.607 回答
2

它不是线程安全的。解决这个问题的最简单方法是用synchronized块包围数组操作。更多关于它的信息:http: //dlang.org/statement.html#SynchronizedStatement

于 2012-04-12T12:17:02.023 回答