Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Execute GO Language Online

package main  
import (  
   "sync"  
   "time"  
  "math/rand"  
   "fmt"  
)  
var wait sync.WaitGroup  
var count int  
//var mutex sync.Mutex  
func  increment(s string)  { 
    start := time.Now()
  //  mutex.Lock() 
   for i :=0;i<10;i++ {  
       
      x := count  
      x++;  
    //rand.Seed(time.Now().UnixNano())
      time.Sleep(time.Duration(rand.Intn(10))*time.Millisecond)  
      count = x;  
      fmt.Println(s, i,"Count: ",count,"time taken: ",time.Since(start))  
    
        
   }  
    // mutex.Unlock()  
   wait.Done()  
     
}  
func main(){  
   wait.Add(2)  
   go increment("foo: ")  
   go increment("bar: ")  
   wait.Wait()  
   fmt.Println("last count value " ,count)  
}  























/*import (
    "crypto/rand"
    "fmt"
)

func main() {
    key := [256]byte{}
    _, err := rand.Read(key[:])
    if err != nil {
        panic(err)
    }
    fmt.Println(key)
}*/



/*...........................................................
generating a random number and sequencse
https://flaviocopes.com/go-random/
.......................................................
.......................................................
.....................................................
.....................................................*/

// for concurrency waitgroup is to hold the 
/* import (  
   "fmt"  
   "time"  
   "sync"  
)  
var wg = sync.WaitGroup{}  
  
func main() {  
   wg.Add(2)  
   go fun1()  
   go fun2()  
   wg.Wait()  
}  
func fun1(){  
   for  i:=0;i<10;i++{  
      fmt.Println("fun1,  ->",i)  
      time.Sleep(time.Duration(5*time.Millisecond))  
   }  
   wg.Done()  
}  
func fun2(){  
   for i:=0;i<10;i++{  
      fmt.Println("fun2,  ->",i)  
      time.Sleep(time.Duration(10*time.Millisecond))  
   }  
   wg.Done()  
} */


/*error handling 
......................................................................

import (  
  "fmt"
   "errors"
  //"math"  
  )
  func sqr(value int) (int, error){
      i:=10
      if(value<=0){
     return 0, errors.New("Math: negative number passed to Sqrt")
      }
  //else{
         i=i/value
          return i,nil
    //  }
 }

  func main(){
 //    i:=10
     result,err:=sqr(3)
     if err !=nil{
    fmt.Println(err)
    }else{
       fmt.Println(result)
       }
   }*/

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.