github.com/ccccaoqing/test@v0.0.0-20220510085219-3985d23445c0/misc/cgo/test/issue1560.go (about)

     1  // Copyright 2011 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package cgotest
     6  
     7  /*
     8  // mysleep returns the absolute start time in ms.
     9  long long mysleep(int seconds);
    10  
    11  // twoSleep returns the absolute start time of the first sleep
    12  // in ms.
    13  long long twoSleep(int);
    14  */
    15  import "C"
    16  
    17  import (
    18  	"testing"
    19  	"time"
    20  )
    21  
    22  var sleepDone = make(chan int64)
    23  
    24  // parallelSleep returns the absolute difference between the start time
    25  // of the two sleeps.
    26  func parallelSleep(n int) int64 {
    27  	t := int64(C.twoSleep(C.int(n))) - <-sleepDone
    28  	if t < 0 {
    29  		return -t
    30  	}
    31  	return t
    32  }
    33  
    34  //export BackgroundSleep
    35  func BackgroundSleep(n int32) {
    36  	go func() {
    37  		sleepDone <- int64(C.mysleep(C.int(n)))
    38  	}()
    39  }
    40  
    41  func testParallelSleep(t *testing.T) {
    42  	sleepSec := 1
    43  	dt := time.Duration(parallelSleep(sleepSec)) * time.Millisecond
    44  	t.Logf("difference in start time for two sleep(%d) is %v", sleepSec, dt)
    45  	// bug used to run sleeps in serial, producing a 2*sleepSec-second delay.
    46  	// we detect if the start times of those sleeps are > 0.5*sleepSec-second.
    47  	if dt >= time.Duration(sleepSec)*time.Second/2 {
    48  		t.Fatalf("parallel %d-second sleeps slept for %f seconds", sleepSec, dt.Seconds())
    49  	}
    50  }