- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Channel synchronization in Golang
We can make use of channels if we want to synchronize goroutines. By synchronizing, we want to make the goroutines work in a defined manner, for example, not starting the next goroutine until the previous one has finished its execution.
The channels help in achieving that, as they can be used to block the process and then can also be used to notify the second goroutine that the previous goroutine has finished its job.
Example 1
Let's consider a very basic example of channel synchronization where we will see how we can achieve it with the help of a buffered channel.
Consider the code shown below.
package main import ( "fmt" "time" ) func check(done chan bool) { fmt.Print("Welcome to...") time.Sleep(time.Second) fmt.Println("TutorialsPoint") done <- true } func main() { done := make(chan bool, 1) go check(done) <-done }
In the above code, we synchronized the code as the <- done is simply blocking the code and unless and until it receives the value, which we are doing inside the check function, it won't let anything else execute.
If we use the command go run main.go on the above code, we will see the following output.
Output
Welcome to...TutorialsPoint
Example 2
The above example can be used to enhance the synchronization further as with it, we can make one goroutine wait for another goroutine.
Consider the code shown below.
package main import ( "fmt" "time" ) func check(done chan bool) { fmt.Print("Welcome to...") time.Sleep(time.Second) fmt.Println("TutorialsPoint") done <- true } func check2() { fmt.Println("Learn Go from here!") } func main() { done := make(chan bool, 1) go check(done) if <-done { go check2() time.Sleep(time.Second) } }
Output
If we use the command go run main.go on the above code, we will see the following output.
Welcome to...TutorialsPoint Learn Go from here!
- Related Articles
- How to close a channel in Golang?
- Hardware Synchronization
- Process Synchronization in Linux
- Process Synchronization in Windows
- Process Synchronization in Solaris
- Thread Synchronization in C#
- Synchronization of ArrayList in C#
- Process Synchronization in C/C++
- Method and Block Synchronization in Java
- Threads and Thread Synchronization in C#
- Synchronization and Pooling of processes in Python
- Print numbers in sequence using thread synchronization
- Synchronization and Pooling of processes in C#
- Synchronization of Alternators by Synchroscope
- Difference between Single Channel and Multi-Channel Marketing
