Golang working with goroutines and channels -4

 We will continue with the last part of golang reading. In our previous examples, we worked with main method which runs on only one processor and all tasks executed sequentially. But what if we need multi task environment which be scheduled by golang get results from these tasks and use them. 

How about Java Future. Sounds familiar ? Most of  the Java developers uses Future interface in order to handle asynchronous processes.

https://www.baeldung.com/java-future

Here is the following a task executor which makes simple math calculation.

public class SquareCalculator { private ExecutorService executor = Executors.newSingleThreadExecutor(); public Future<Integer> calculate(Integer input) { return executor.submit(() -> { Thread.sleep(1000); return input * input; }); } }

What about execution ? It is so easy to implement. After creating an instance of executor we trigger "calculate" method and after  we expect the result from "get" method of Future interface. Very cool.

Future<Integer> future = new SquareCalculator().calculate(10); while(!future.isDone()) { System.out.println("Calculating..."); Thread.sleep(300); } Integer result = future.get();

Comparing to Java,  In Golang "goroutine" has executor role and "channel" has a Future role. So lets have a look at an example of goroutine and channel.


package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {

//We will create a channel which will takes the result of the calculation
// It is "int" type and never gets any other type.

    c := make(chan int)

// Prepare rounding mechanism by using time (you may investigate "seed" term in
// golang). So we pass generated int type and channel itself so that we can return
// to main function.

    for i := 0; i < 5; i++ {
        time.Sleep(1 * time.Second)
        source := rand.NewSource(time.Now().UnixNano())
        r := rand.New(source)
        g := r.Intn(50)
        fmt.Println(g, " will be calculated ")
        go calculate(g, c)
    }

// We are waiting results from calculate method "<-c" by operation.

    for i := 0; i < 5; i++ {

        fmt.Println(<-c, " is the result ")

    }

}

// No return function as you see. It will be enough to pass the result to channel.

func calculate(s int, c chan int) {
    c <- s * s

}






Have a good work.






Yorumlar

Bu blogdaki popüler yayınlar

IONIC BAŞLANGIÇ

Cannot resolve the collation conflict between “Turkish_CI_AS” and “SQL_Latin1_General_CP1_CI_AS” in the equal to operation

Golang working with interfaces and functions -3