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

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  )
     7  
     8  const LOOPS = 50
     9  
    10  var shared int
    11  
    12  func main() {
    13      // Creates a goroutine that performs the add function 50 times
    14  	go op(add)
    15      // Creates a goroutine that performs the sub function 50 times
    16  	go op(sub)
    17      // Creates a goroutine that performs the mul function 50 times
    18  	go op(mult)
    19      // Sleeps for 10s
    20  	time.Sleep(10 * time.Second)
    21      // Prints the final value of shared.
    22  	fmt.Println("---------Final value was",shared)
    23  }
    24  
    25  func op(oper func(int, int)) {
    26  	for i:=1;i<LOOPS;i++{
    27  		oper(1, i)
    28  	}
    29  }
    30  
    31  // Adds the value 'n' to the shared variable then sleeps for 1ms
    32  func add(n int, i int) {
    33  	shared += n
    34  	fmt.Println("--------Iteration", i," Add value is :", shared)
    35  	time.Sleep(time.Millisecond)
    36  }
    37  
    38  // Subtracts the value 'n' from the shared variable then sleeps for 1ms
    39  func sub(n int, i int) {
    40  	shared -= n
    41  	fmt.Println("--------Iteration", i, " Sub value is :", shared)
    42  	time.Sleep(time.Millisecond)
    43  }
    44  
    45  // Multiplies the shared variable with the value 'n' then sleeps for 1ms
    46  func mult(n int, i int) {
    47  	shared *= n
    48      fmt.Println("--------Iteration", i, " Mult value is :", shared)
    49  	time.Sleep(time.Millisecond)
    50  }
    51