Can I concurrently write different slice elements

前端 未结 2 1761
野趣味
野趣味 2020-11-30 08:56

I have a slice that contains work to be done, and a slice that will contain the results when everything is done. The following is a sketch of my general process:

<         


        
相关标签:
2条回答
  • 2020-11-30 09:21

    The rule is simple: if multiple goroutines access a variable concurrently, and at least one of the accesses is a write, then synchronization is required.

    Your example does not violate this rule. You don't write the slice value (the slice header), you only read it (implicitly, when you index it).

    You don't read the slice elements, you only modify the slice elements. And each goroutine only modifies a single, different, designated slice element. And since each slice element has its own address (own memory space), they are like distinct variables. This is covered in Spec: Variables:

    Structured variables of array, slice, and struct types have elements and fields that may be addressed individually. Each such element acts like a variable.

    What must be kept in mind is that you can't read the results from the results slice without synchronization. And the waitgroup you used in your example is a sufficient synchronization. You are allowed to read the slice once wg.Wait() returns, because that can only happen after all worker goroutines called wg.Done(), and none of the worker goroutines modify the elements after they called wg.Done().

    For example, this is a valid (safe) way to check / process the results:

    wg.Wait()
    // Safe to read results after the above synchronization point:
    fmt.Println(results)
    

    But if you would try to access the elements of results before wg.Wait(), that's a data race:

    // This is data race! Goroutines might still run and modify elements of results!
    fmt.Println(results)
    wg.Wait()
    
    0 讨论(0)
  • 2020-11-30 09:24

    Yes, it's perfectly legal: a slice has an array as its underlying data storage, and, being a compound type, an array is a sequence of "elements" which behave as individual variables with distinct memory locations; modifying them concurrently is fine.

    Just be sure to synchronize the shutdown of your worker goroutines with the main one before it reads the updated contents of the slice.

    Using sync.WaitGroup for this—as you do—is perfectly fine.

    Also, as @icza said, you must not modify the slice value itself (which is a struct containing a pointer to the backing storage array, the capacity and the length).

    0 讨论(0)
提交回复
热议问题