Concurrency isn’t Always Faster in Go

Go Scheduling

  • Concurrent — Two or more threads can start, run, and complete in overlapping time periods.
  • Parallel — The same task can be executed multiple times at once.
  • All the threads can consume CPU cycles without being starved for too much time.
  • The workload is distributed as evenly as possible among the different CPU cores.
  • G — Goroutine
  • M — OS thread (stands for machine)
  • P — CPU core (stands for processor)
  • Executing — The goroutine is scheduled on an M and executing its instructions.
  • Runnable — The goroutine is waiting to be in an executing state.
  • Waiting — The goroutine is stopped and pending something completing, such as a system call or a synchronization operation (such as acquiring a mutex).
Figure 1 — An example of the current state of a Go application executed on a four-core machine. Goroutines that aren’t in an executing state are either runnable (pending being executed) or waiting (pending a blocking operation)

Parallel Merge Sort

Figure 2 — Applying the merge sort algorithm repeatedly breaks each list into two sublists. Then the algorithm uses a merge operation such that the resulting list is sorted
Benchmark_sequentialMergesort-4       2278993555 ns/op
Benchmark_parallelMergesortV1-4 17525998709 ns/op
Benchmark_sequentialMergesort-4       2278993555 ns/op
Benchmark_parallelMergesortV1-4 17525998709 ns/op
Benchmark_parallelMergesortV2-4 1313010260 ns/op
About the author
https://twitter.com/teivah

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Teiva Harsanyi

Teiva Harsanyi

Software Engineer @Docker 🐳 | 📖 100 Go Mistakes author | 改善