search
HomeBackend DevelopmentGolangGO: 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:

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
}()

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 



<p>Practical example:<br>
</p>

<pre class="brush:php;toolbar:false">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 



<p>The output of this code would be<br>
</p>

<pre class="brush:php;toolbar:false">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!

Statement
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
Learn Go String Manipulation: Working with the 'strings' PackageLearn Go String Manipulation: Working with the 'strings' PackageMay 09, 2025 am 12:07 AM

Go's "strings" package provides rich features to make string operation efficient and simple. 1) Use strings.Contains() to check substrings. 2) strings.Split() can be used to parse data, but it should be used with caution to avoid performance problems. 3) strings.Join() is suitable for formatting strings, but for small datasets, looping = is more efficient. 4) For large strings, it is more efficient to build strings using strings.Builder.

Go: String Manipulation with the Standard 'strings' PackageGo: String Manipulation with the Standard 'strings' PackageMay 09, 2025 am 12:07 AM

Go uses the "strings" package for string operations. 1) Use strings.Join function to splice strings. 2) Use the strings.Contains function to find substrings. 3) Use the strings.Replace function to replace strings. These functions are efficient and easy to use and are suitable for various string processing tasks.

Mastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMay 09, 2025 am 12:02 AM

ThebytespackageinGoisessentialforefficientbyteslicemanipulation,offeringfunctionslikeContains,Index,andReplaceforsearchingandmodifyingbinarydata.Itenhancesperformanceandcodereadability,makingitavitaltoolforhandlingbinarydata,networkprotocols,andfileI

Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use