github.com/DARA-Project/GoDist-Scheduler@v0.0.0-20201030134746-668de4acea0d/examples/sharedIntegerChannel_test/sharedIntegerChannel.go (about)

     1  package main
     2  
     3  /*
     4  This is a test of thread non-determinism; threads communicate on a
     5  shared channel, and perform operations on a shared resource. The
     6  purpose of this test is to demonstrate that GoDist has the ability to
     7  accuratly replay the thread schedule of a single process which
     8  communicates on channels
     9  
    10  BUG This test seems to be deterministic automatically when run with
    11  GOMAXPROCS set to 1, which makes it a bad test becuase a simplifing
    12  assumptions about GoDist is that the execution will be serialized i.e
    13  GOMAXPROCS will allways equal 1. This fact makes this a bad test.
    14  */
    15  
    16  
    17  import (
    18  	"log"
    19  	"time"
    20  )
    21  
    22  const LOOPS = 50
    23  const THREADS = 3
    24  
    25  var shared int
    26  var comm chan int
    27  
    28  func main() {
    29  	comm = make(chan int, THREADS)
    30  	// Create new goroutine that runs add function 50 times
    31      go op(add)
    32  	// Create new goroutine that runs sub function 50 times
    33  	go op(sub)
    34  	// Create new goroutine that runs mult function 50 times
    35  	go op(mult)
    36  	comm <- 1
    37  	comm <- 2
    38  	comm <- 3
    39  	log.Println("Main thread about to sleep")
    40  	time.Sleep(3 * time.Second)
    41  	log.Println(shared)
    42  }
    43  
    44  func op(oper func(int)) {
    45  	for i:=1;i<LOOPS;i++{
    46  		val := <- comm
    47  		oper(val)
    48  		comm <- shared + i
    49  		//time.Sleep(time.Nanosecond)
    50  	}
    51  }
    52  
    53  func add(n int) {
    54  	shared += n
    55  	log.Println("add ->",shared)
    56  }
    57  
    58  func sub(n int) {
    59  	shared -= n
    60  	log.Println("sub ->",shared)
    61  }
    62  
    63  func mult(n int) {
    64  	shared *= n
    65  	log.Println("mult ->",shared)
    66  }
    67  
    68  
    69  
    70