go runtime in shared libs functions called in threads

96 views
Skip to first unread message

Peter Galbavy

unread,
Oct 19, 2022, 9:28:20 AM10/19/22
to golang-nuts
I have built a shared lib in Go to replace an old thing we use to send email - mainly to modernise things and add TLS and authentication. We run each call to the entry point in it's own thread in the main program.

I am both curious but also concerned about what happens here with go runtimes. I presume each thread has it's own runtime, and on exit it is torn down, but I may be wrong and would like to know more.

Thanks!

Amnon

unread,
Oct 19, 2022, 5:04:02 PM10/19/22
to golang-nuts
Each thread has its own stack, but little else.

Konstantin Khomoutov

unread,
Oct 20, 2022, 7:28:12 AM10/20/22
to Peter Galbavy, golang-nuts
As already hinted, there's only a single instance of the Go runtime powering
your shared library after it got loaded and initialized. Basically it's the
same thing as a regular Go program would call into a C library via cgo, and
that library would be using multiple running threads which could access the
data passed from the Go side and even call back to the Go side.

To have less cognitive burden, I would recommend to move one step further and
make your library have a single entry point which would accept a job unit and
process it concurrently with any other job units - that is, defer concurrency
to the Go library.

If you're basically already doing something like this and are only concerned
about what happens when you call to a Go library from multiple threads, then
the answer is - apply the usual logic: all variables which are local to the
function call chain which got called from a thread are safe as they are not
shared from the other call chains. If these call chains happen to share some
state in the library, you have to guared the access to it - in one way or
another - using channels or resorting to mutexes etc.

Peter Galbavy

unread,
Oct 20, 2022, 11:26:12 AM10/20/22
to golang-nuts
Thanks for the detail. We cannot change the calling program, just conform to it's API, so it's one function call per email send event and each in it's own (new) thread.
Reply all
Reply to author
Forward
0 new messages