A
A
Andrey2018-11-20 23:31:39
go
Andrey, 2018-11-20 23:31:39

How to find the pid of the process that the goroutine is executing?

Hello.
There is a code that runs 4 goroutines (there are 2 physical and 4 virtual cores on the machine), how to find out the process id that executes the goroutine?
A total of 8 child processes are running, 4 of which take up about 100% of the CPU.
there is this code:

package main

import (
  "fmt"
  "math/rand"
  "os"
)

func main() {

  source := make(chan string)

  items := [...]string{
    "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "l", "k", "j",
    "h", "g", "f", "d", "s", "a", "z", "x", "c", "v", "b", "n", "m",
  }

  for i := 0; i < 4; i++ {

    go func(source <-chan string, i int) {

      for {

        arg := <-source

        abc(arg, i, os.Getpid())
      }
    }(source, i)
  }

  for k := 0; k < 1000; k++ {
    for _, value := range items {
      source <- value
    }
  }
}

func abc(arg string, i int, pid int) {

  for j:=0; j<1000000; j++ {

    rnd := rand.Intn(30000)
  }

  fmt.Printf("[%v][%d] %s\n", pid, i, arg)
}

It works like this:
5bf47f8c0c374619053680.png
And it gives out like this:
5bf48085edfb6666855569.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2018-11-20
@dasha_programmist

call os.Getpid() from the goroutines themselves

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question