GO: Concurrency vs Parallelism For Dummies.

WBOY
Release: 2024-08-23 12:30:31
Original
626 people have browsed it

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!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!