sonumb

macos Go에서 gettid() 호출 본문

개발자 이야기/Go

macos Go에서 gettid() 호출

sonumb 2021. 10. 27. 14:48

macos 용 go에서는 syscall.Gettid() 가 없음..
따라서, Gettid() 함수를 만들어야 한다.

macos는 SYS_GETTID를 이용해서 syscall()을 호출하면 -1이 리턴되므로 사용불가..

 

 


대체할 수 있는 시스템콜은 thread_selfid()라는 시스템콜이다. (리눅스의 제공여부는 확인하지 않았다)

 

아래는 소스코드

// +build darwin
// 다른 unix 계열은 아래 라인을 집어 넣은 후, syscall.Gettid()호출 및 반환하게 한다.
////// +build aix dragonfly freebsd linux netbsd openbsd solaris
// Above OSs will call syscall.Gettid() and return.

import (
  "fmt"
  "runtime"
  "sync"
  "syscall"
  "time"
)

func Gettid_org() (tid int) {
  r0, _, _ := syscall.RawSyscall(syscall.SYS_GETTID, 0, 0, 0)
  tid = int(r0)
  return
}

func Gettid_thread_selfid() (tid int) {
  r0, _, _ := syscall.RawSyscall(syscall.SYS_THREAD_SELFID, 0, 0, 0)
  tid = int(r0)
  return
}

func main() {
  runtime.GOMAXPROCS(runtime.NumCPU())

  var wg sync.WaitGroup

  for i := 0; i < 10; i++ {
    wg.Add(1)
    go func() {
      defer wg.Done()
      runtime.LockOSThread()
      defer runtime.UnlockOSThread()
      fmt.Println("gettid():",Gettid_org(),",   thread_selfid():",Gettid_thread_selfid())
      time.Sleep(3 * time.Second)
    }()
  }
  wg.Wait()
}

결과는 아래와 같다.

$ uname 
Darwin

$ go build gettid.go; ./gettid
gettid(): -1 ,   thread_selfid(): 126658
gettid(): -1 ,   thread_selfid(): 126656
gettid(): -1 ,   thread_selfid(): 126661
gettid(): -1 ,   thread_selfid(): 126640
gettid(): -1 ,   thread_selfid(): 126665
gettid(): -1 ,   thread_selfid(): 126657
gettid(): -1 ,   thread_selfid(): 126660
gettid(): -1 ,   thread_selfid(): 126664
gettid(): -1 ,   thread_selfid(): 126666
gettid(): -1 ,   thread_selfid(): 126662
반응형