Concurrent programming knowledge a necessity these days. Servers need to handle multiple connections and process them simultaniously. Mobile apps are working in a manner that, foreground and backgroung processing is done in saperate context. Since processors are growing in numbers not in speed, we need to design out programs in such a manner.
Go let us use two types of Concurrent Programming:
1. Communicating sequential processes (CSP).
2. Shared memory multi-threaded programming (Traditional).
Goroutines
Goroutines are not threads, but they are like threads. Each concurrently executing activity is called Goroutine. As an example assume a problem in which we are processing multiple types of data and writing in multiple files. So, there are two ways to do that.
- Sequential programming.
- Concurrent programming.
I will just create an example, and will show you it’s really easy to convert a sequential program to concurrent program in go.
A concurrent file writing program:
Sequential Implementation:
package main import ( "os" "fmt" ) var filenamearray []string func processData(index int) { f, _ := os.OpenFile(filenamearray[index],os.O_RDWR | os.O_CREATE,0777) // skipping error defer f.Close() for i := 0;i<10000000;i++ { a := i + index fmt.Fprintln(f,a) } } func main() { filenamearray = []string{"a1", "a2", "a3","a4"} for i:=0;i<len(filenamearray) ;i++ { processData(i) } }
Concurrent Implementation:
import ( "os" "fmt" "sync" ) var filenamearray []string var wg sync.WaitGroup func processData(index int) { f, _ := os.OpenFile(filenamearray[index],os.O_RDWR | os.O_CREATE,0777) // skipping error defer wg.Done() defer f.Close() for i := 0;i<10000000;i++ { a := i + index fmt.Fprintln(f,a) } } func main() { filenamearray = []string{"a1", "a2", "a3","a4"} for i:=0;i<len(filenamearray) ;i++ { wg.Add(1) go processData(i) } wg.Wait() }
When I tried to run both the programs, there was a huge difference in performance:
Sequential took : 1 Minute and 21 seconds approx.
Concurrent took : 28 seconds.
You can test by changing the number of files.
I the next part I will cover channels, with a practical example. Till then, Happy Coding.
[…] Golang Concurrency Part I, I said Goroutines are not threads. In this post I will explain the […]
LikeLike
[…] Part I, we just converted a sequential program to a multithreaded one and did it with a very simple […]
LikeLike