Golang — spread concurrently goroutine for every seconds

Nova Herdi Kusumah
2 min readJul 1, 2021

Concurrent programming is one of the golang great feature that it has, and it really help developer a lot. In this article i want to share about my exiting experience with this feature.

Goroutine is the best feature that golang have for software developer right now, i mean it no need other third party app to run concurrent function call, it just like as simple as go functionName().

Problem that we had is that we are having huge data but we don’t wanna just send the goroutine to do the concurrent function with all data at the same time, instead we wanna spread the concurrent goroutine every second.

To be noted in this article, we are not using WaitGroup or Mutex but we will using only goroutine as an asynchronous programming, because WaitGroup or Mutex it will make the go routine to be synchronous.

This is the example of the goroutine code

https://tour.golang.org/concurrency/1

In this article i will split the section into 2 parts :

  1. How to batching the array for sending concurrent function call every second
  2. Create the goroutine to call in every second

And at the last reading i will give you the whole code of this article

1. How to batching the array for sending concurrent function call every second

Let say data that we have is 30 integer and we will spread the data into 10 seconds, first we wanna initiate the variables in the file like the following :

Here we introduce you with import, var, and init() as the basic of the golang syntax, you can click on the link for further reading that will not explained in this article.

2. Create the goroutine to call in every second

After we have done the initializing all the variables, now it’s time for us to spread the data batch into every each second and send the number of concurrent goroutine into it.

  • printData(i) function acting as the goroutine function
  • min(a,b) function is to check for the array index is out of scope or not
  • main() function is the main function that will called every time we run the file

Inside the main() function we have time.Sleep(time.Second * 1) that is the main syntax to spread the batch of data delayed in every 1 second.

And also we have go printData(dt) that is the goroutine that we will send every second.

BONUS:
To play around, click here => https://play.golang.org/p/ZszUst5wfpI

Thanks for reading.

--

--