Why not sync.Mutex is designed as an interface

229 views
Skip to first unread message

Xie Yuchen

unread,
Nov 8, 2022, 10:55:13 AM11/8/22
to golang-nuts
I checked with the issue about how to refer no-copy and the check of cmd/vet. After checking, I'm curious that why not define mutex as an interface, as interface always copy like a reference, which means users don't worry to copy by value and cause an error.

Design by the interface can always copy like a reference and no need to mark it as cannot copy. However, we need to provide a default implementation of the mutex and the construction of mutex is not short and clean anymore.

Would like to see how do you think about this confusion. 

Regrads

TheDiveO

unread,
Nov 8, 2022, 12:02:08 PM11/8/22
to golang-nuts
From my limited experience, I notice two things:
  1. I've rarely ever seen the need arise in my limited own experience to copy objects that would like to share their mutex. I would rather consider this to be most of the time a design issue, but I will be happy to stand corrected. The rationale to me in these cases is that the mutex is protecting a set of information closely "locked" to the lock it is protecting it. When do you even copy the information? Surely not while you don't have the lock, but then you end up with a locked copy. Now, if the copies reference the same lock, what does that really mean? You have two copies of the information, yet a single lock? Why then not having a single source of information with a single lock or two sets of information that can develop independently and have their own locks?
  2. Due to the way Interfaces work in Go you can define your own Mutex interface and then sync.Mutex will be one implementation of it. (I hope that I didn't miss something here, but that is what immediately came to my mind.)

Ian Lance Taylor

unread,
Nov 8, 2022, 12:11:35 PM11/8/22
to Xie Yuchen, golang-nuts
That would mean that the zero value of sync.Mutex would not be usable.

Ian

Yuchen Xie

unread,
Dec 16, 2022, 11:30:03 AM12/16/22
to golang-nuts
That makes sense. Thanks for replying.
regards
Reply all
Reply to author
Forward
0 new messages