Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/cgo: is lock/unlock mutex in different OS thread safe #30337

Closed
winglq opened this issue Feb 21, 2019 · 2 comments
Closed

cmd/cgo: is lock/unlock mutex in different OS thread safe #30337

winglq opened this issue Feb 21, 2019 · 2 comments

Comments

@winglq
Copy link

winglq commented Feb 21, 2019

What version of Go are you using (go version)?

$ go version
go version go1.11.5 linux/amd64

Does this issue reproduce with the latest release?

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GOHOSTARCH="amd64"
GOHOSTOS="linux"

What did you do?

I am wondering whether the following steps are safe:

  1. in one go routine lock Mutex M, and then pass M's pointer and a golang exported function(with //export functionName above the function) to a cgo function, lock M again. The go routine will be blocked.
  2. after the c library recived the M's pointer and exported function, it starts to do some background job, after the job is completed, it will call the exported function and pass M's pointer as a parameter.
  3. the exported function will unlock the Mutex
  4. the blocked go routine will be unblocked.

You could find the specific code in this patch, if I do not make it clear.

The sync.Mutex is locked in one go routine and uncloked is called in a go exported function which is called by a c library. Will the exported function be scheduled to the original OS thread which owns the blocked go routine? Or is lock/unlock sync.Mutex in different OS thread safe? I know it's safe to lock/unlock sync.Mutex in different go routines, but lock/unlock mutex(OS) in different pthreads is not safe.

@ianlancetaylor
Copy link
Contributor

It's fine to lock and unlock a sync.Mutex in different operating system threads. Since goroutines move between threads unpredictably, it would be quite painful to use sync.Mutex if you were required to always access it on the same thread.

Note that we don't use our issue tracker for questions, and it's generally better to ask questions in a forum. You will typically get faster and better answers. See https://golang.org/wiki/Questions.

@winglq
Copy link
Author

winglq commented Feb 21, 2019

Sorry for the wrong place and thanks for the quick response.

@golang golang locked and limited conversation to collaborators Feb 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants