GO: Concurrency vs Parallelism For Dummies.
Welcome to this post with a somewhat degrading title.
But, in this post I want to explain to you what these 2 characteristics of programming are in a very simple way, this time using my favorite programming language GOLANG.
Let's imagine a kitchen:
Cooking a dish: This represents a task.
A cook: He is a processor.
Attendance:
Several cooks in the kitchen: Each one preparing a different dish.
In Go: Every cook would be a goroutine. Although the kitchen (processor) only has one oven, cooks can work on their dishes simultaneously, passing time on other tasks while waiting for the oven to become available.
Parallelism:
Various ovens: Each cook has his own oven.
In Go: If we have multiple physical processors, each goroutine could run on a different processor, cooking several dishes at the same time in a real way.
What's the difference?
Concurrency: Tasks are executed intertwined, giving the illusion of parallelism, even on a single processor.
Parallelism: Tasks run simultaneously on multiple processors, which significantly speeds up the process.
How to use them in Go?
Goroutines: They are like light threads. To create a goroutine, we simply use the go keyword before a function:
Let's see an example of how we can use goroutines in golang:
go func() { // Código que se ejecutará en una goroutine }()
Channels: These are pipes through which goroutines can communicate and synchronize.
Imagine that they are tubes to pass ingredients between the cooks
ch := make(chan int) go func() { ch <- 42 // Enviar un valor por el canal }() value := <-ch // Recibir un valor del canal
Practical example:
package main import ( "fmt" "time" ) func worker(id int, c chan int) { for n := range c { fmt.Printf("Worker %d received %d\n", id, n) time.Sleep(time.Second) } } func main() { c := make(chan int) for i := 1; i <= 5; i++ { go worker(i, c) } for n := 1; n <= 10; n++ { c <- n } close(c) time.Sleep(time.Second) }
The output of this code would be
Worker 1 received 1 Worker 2 received 2 Worker 3 received 3 Worker 4 received 4 Worker 5 received 5 Worker 1 received 6 Worker 2 received 7 Worker 3 received 8 Worker 4 received 9 Worker 5 received 10
although sometimes it could look like this
Worker 5 received 1 Worker 1 received 3 Worker 2 received 2 Worker 4 received 5 Worker 3 received 4 Worker 3 received 6 Worker 5 received 10 Worker 2 received 8 Worker 4 received 7 Worker 1 received 9
or like this
Worker 5 received 1 Worker 1 received 2 Worker 2 received 3 Worker 3 received 4 Worker 4 received 5 Worker 1 received 6 Worker 2 received 7 Worker 3 received 8 Worker 5 received 9 Worker 4 received 10
Why does the output change every time I run the program?
The main reason why the program output changes each run is due to the non-deterministic nature of concurrency.
Here's a breakdown of what's happening:
Create a channel: make(chan int) creates a channel of integers. This channel will be used for communication between goroutines.
Start goroutines: The loop for i := 1; i The worker function receives the ID and channel.
Send values to channel: The loop for n := 1; n 1 to 10 to the channel.
Close the channel: The close(c) call closes the channel, indicating that no more values will be sent.
Receive values from channel: Each goroutine receives values from the channel using the for n := range c loop. When a value is received, it is printed to the console.
Wait for goroutines to finish: The time.Sleep(time.Second) call ensures that the main goroutine waits for the other goroutines to finish before exiting.
So far:
We create 5 goroutines (cooks) that receive numbers through a channel.
We send numbers to the channel for the cooks to process.
The cooks work concurrently, processing the numbers as they receive them.
Why use concurrency and parallelism in Go?
Better performance: Especially in I/O-bound tasks (such as reading files or making HTTP requests).
Increased responsiveness: The application can continue to respond to other requests while a task is locked.
More scalable architectures: You can distribute work across multiple cores or machines.
Remember!
Concurrency and parallelism are powerful tools, but they can also make code more complex to understand and debug. It is important to use them carefully and understand their implications.
Do you want to go deeper into a specific topic?
We can explore concepts like:
Synchronization: Mutexes, work groups, etc.
Concurrency patterns: Producer-consumer, pipeline, etc.
Concurrent Testing: How to Test Concurrent Code Effectively.
Greetings,
Lucatonny Raudales
X/Twitter
Github
The above is the detailed content of GO: Concurrency vs Parallelism For Dummies.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
