Is this a safe way to block main thread but not main goroutine?

233 views
Skip to first unread message

Akhil Indurti

unread,
Apr 29, 2020, 4:18:54 PM4/29/20
to golang-nuts
I want to run the main goroutine on another thread besides the main thread, so that the main thread can block in darwin UI code. Is this a safe way to do it?

package main

/*
#include <pthread.h>
#include <stdio.h>

void block() {
	printf("Blocking main thread? %d\n", pthread_main_np());
	while(1);
}
*/
import "C"
import (
	"fmt"
	"runtime"
)

func init() {
	runtime.LockOSThread()
	go main()
	C.block()
}

func main() {
	fmt.Println("Blocking main goroutine?", C.pthread_main_np())
}

This prints out the following:
$ go run threadtrick.go
Blocking main thread? 1
Blocking main goroutine? 0

Thomas Bushnell, BSG

unread,
Apr 29, 2020, 4:38:27 PM4/29/20
to Akhil Indurti, golang-nuts
That seems needlessly complex. Why not just skip the weird init, and just have main do a go to the thing you want to be not on the main thread, and let the main thread do its thing?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/6b476ab1-c6b6-4f77-91d8-aba2dfbcc314%40googlegroups.com.

Akhil Indurti

unread,
Apr 29, 2020, 4:43:39 PM4/29/20
to golang-nuts
I want to mirror (or control) the event loop inside the main goroutine. The main goroutine should be the one to block for events. Plus, as long as it's safe, it doesn't seem needlessly complex to me.
To unsubscribe from this group and stop receiving emails from it, send an email to golan...@googlegroups.com.

Marcin Romaszewicz

unread,
Apr 29, 2020, 5:18:35 PM4/29/20
to Akhil Indurti, golang-nuts
As Thomas said, this will work for sure, though, and doesn't require any manual setup, and you don't need to do funny business with CGO.

func main() {
  go doAllYourOtherStuff()
  blockOnDarwinEventLoop()
}

Done.


To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/5e80ed26-09c5-4133-875e-4b0f72e9e2af%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages