Home Backend Development Golang GO: Concurrency vs Parallelism For Dummies.

GO: Concurrency vs Parallelism For Dummies.

Aug 23, 2024 pm 12:30 PM

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:

GO: Concurrencia vs Paralelismo Para Tontos.

Let's see an example of how we can use goroutines in golang:

go func() {
    // Código que se ejecutará en una goroutine
}()
Copy after login

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
Copy after login

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)
}
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

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 vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

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 and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

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.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

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

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

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.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

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 vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

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.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

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.

See all articles