Map and slice are also concurrency-unsafe data structures. Why is map designed to throw a fatal that cannot be recovered when there is a concurrency conflict, but slice does not have any prompt? Are there any design considerations?

228 views
Skip to first unread message

fliter

unread,
Jun 2, 2023, 7:59:07 AM6/2/23
to golang-nuts
Map and slice are also concurrency-unsafe data structures. Why is map designed to throw a fatal that cannot be recovered when there is a concurrency conflict, but slice does not have any prompt? Are there any design considerations?

Thanks!

Brian Candler

unread,
Jun 2, 2023, 8:50:57 AM6/2/23
to golang-nuts
Is it actually "designed" to do that? I think it just crashes when the map data structure is in a corrupted state, because of concurrent updates.

In principle, you may be able to get a panic when updating a slice concurrently, but it's much rarer. That's because a slice allocates a contiguous area of memory for N (cap) elements, so normally the slice data structure itself (which contains the pointer/cap/len) is not being modified, just the area of memory that it points to. That means that you could end up with an element of the slice containing a corrupted value, but the slice itself would not be corrupt. Also, operations which re-slice or append to the slice return a new slice structure - which may or may not point to the original allocated memory.

The race detector is helpful to identify any unsafe concurrent operations, to variables of any type.

Ian Lance Taylor

unread,
Jun 2, 2023, 11:47:14 AM6/2/23
to fliter, golang-nuts
On Fri, Jun 2, 2023 at 4:59 AM fliter <imc...@gmail.com> wrote:
>
> Map and slice are also concurrency-unsafe data structures. Why is map designed to throw a fatal that cannot be recovered when there is a concurrency conflict, but slice does not have any prompt? Are there any design considerations?

Because some cases are easy and cheap to detect for maps, but there
are no cases that are easy or cheap to detect for slices.

Ian

fliter

unread,
Jun 2, 2023, 11:22:41 PM6/2/23
to golang-nuts
Thank you for your perfect answer

fliter

unread,
Jun 2, 2023, 11:23:02 PM6/2/23
to golang-nuts
Thank you for your perfect answer

Reply all
Reply to author
Forward
0 new messages