github.com/choleraehyq/pid@v0.0.18/pid_go1.5_test.go (about)

     1  // Copyright 2022 Cholerae Hu.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    12  // implied. See the License for the specific language governing
    13  // permissions and limitations under the License. See the AUTHORS file
    14  // for names of contributors.
    15  
    16  //go:build gc && go1.5
    17  // +build gc,go1.5
    18  
    19  package goid
    20  
    21  import (
    22  	"fmt"
    23  	"testing"
    24  	"unsafe"
    25  )
    26  
    27  var _ = unsafe.Sizeof(0)
    28  
    29  //go:linkname procPin runtime.procPin
    30  //go:nosplit
    31  func procPin() int
    32  
    33  //go:linkname procUnpin runtime.procUnpin
    34  //go:nosplit
    35  func procUnpin()
    36  
    37  func getTID() int {
    38  	tid := procPin()
    39  	procUnpin()
    40  	return tid
    41  }
    42  
    43  func TestParallelGetPid(t *testing.T) {
    44  	ch := make(chan *string, 100)
    45  	for i := 0; i < cap(ch); i++ {
    46  		go func(i int) {
    47  			id := GetPid()
    48  			expected := getTID()
    49  			if id == expected {
    50  				ch <- nil
    51  				return
    52  			}
    53  			s := fmt.Sprintf("Expected %d, but got %d", expected, id)
    54  			ch <- &s
    55  		}(i)
    56  	}
    57  
    58  	for i := 0; i < cap(ch); i++ {
    59  		val := <-ch
    60  		if val != nil {
    61  			t.Fatal(*val)
    62  		}
    63  	}
    64  }
    65  
    66  func TestGetPid(t *testing.T) {
    67  	p1 := GetPid()
    68  	p2 := getTID()
    69  	if p1 != p2 {
    70  		t.Fatalf("The result of GetPid %d procPin %d are not equal!", p1, p2)
    71  	}
    72  }
    73  
    74  func BenchmarkGetPid(b *testing.B) {
    75  	for i := 0; i < b.N; i++ {
    76  		GetPid()
    77  	}
    78  }
    79  
    80  func BenchmarkParallelGetPid(b *testing.B) {
    81  	b.RunParallel(func(pb *testing.PB) {
    82  		for pb.Next() {
    83  			GetPid()
    84  		}
    85  	})
    86  }