English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang 基础教程

Golang 控制语句

Golang 函数 & 方法

Golang 结构体

Golang 切片 & 数组

Golang 字符串(String)

Golang 指针

Golang 接口

Golang 并发

Golang 异常(Error)

Golang 其他杂项

Concurrencia (Goroutines) de Go

Go语言提供了称为Goroutines的特殊功能。Goroutine是一种函数或方法,可与程序中存在的任何其他Goroutine一起独立且同时执行。换句话说,每个Go语言中同时执行的活动称为Goroutines,您可以将Goroutine视为轻量级线程。与线程相比,创建Goroutines的成本非常小。每个程序至少包含一个Goroutine,并且该Goroutine被称为主Goroutine。如果主Goroutine终止,则所有Goroutine在主Goroutine之下运行,那么程序中存在的所有goroutine也将终止;Goroutine始终在后台运行。

如何创建Goroutine?

您只需使用go关键字作为函数或方法调用的前缀,即可创建自己的Goroutine,如以下语法所示:

Sintaxis:

func name(){
// Sentencia
}
// 在函数名前面,使用go关键字
go name()
package main 
  
import "fmt"
  
func display(str string) { 
    for w := 0; 6; w++ { 
        fmt.Println(str) 
    } 
} 
  
func main() { 
  
    // Llamar a Goroutine 
    go display("Bienvenido") 
  
    //正常调用函数
    display("oldtoolbag.com) 
}

Salida:

oldtoolbag.com
oldtoolbag.com
oldtoolbag.com
oldtoolbag.com
oldtoolbag.com
oldtoolbag.com

在上面的示例中,我们仅创建了display()函数,然后以两种不同的方式调用此函数,第一种是Goroutine,即go display("Welcome"),另一种是常规调用函数,即display("w3codebox)

但是您可能发现问题了,它只显示调用普通函数的结果,而不显示Goroutine的结果,因为执行新的Goroutine时,Goroutine调用会立即返回。它不像普通函数那样等待Goroutine完成执行,它们总是在Goroutine调用后一直前进到下一行,并忽略Goroutine返回的值。因此,为了正确执行Goroutine,我们对程序进行了一些更改,如以下代码所示:

修改后的Goroutine示例:

package main 
  
import ( 
    "fmt"
    "time"
) 
  
func display(str string) { 
    for w := 0; 6; w++ { 
        time.Sleep(1 * time.Second) 
        fmt.Println(str) 
    } 
} 
  
func main() { 
  
    // Llamar a Goroutine 
    go display("Bienvenido") 
  
    //Llamar a función común
    display("w3codebox) 
}

Salida:

Bienvenido
w3codebox
w3codebox
Bienvenido
Bienvenido
w3codebox
w3codebox
Bienvenido
Bienvenido
w3codebox
w3codebox

Añadimos el método Sleep() en el programa, que hace que el Goroutine principal espere mientras se ejecuta el nuevo Goroutine1segundos entre sueño1segundos, muestra la bienvenida en la pantalla y luego1El Goroutine principal reprograma y ejecuta sus operaciones después de <6Después de que el Goroutine principal termina. Aquí, el Goroutine y la función común trabajan al mismo tiempo.

Ventajas de las Goroutines

  • Las Goroutines tienen un costo menor que los hilos.

  • Las Goroutines se almacenan en pilas y el tamaño de la pila puede aumentar y disminuir según las necesidades del programa. Sin embargo, en un hilo, el tamaño de la pila es fijo.

  • Las Goroutines pueden comunicarse mediante canales, y estos canales están diseñados de manera especial para evitar conflictos al acceder a memoria compartida usando Goroutines.

  • Supongamos que un programa tiene un hilo y este hilo tiene muchos Goroutines asociados. Si cualquier Goroutine bloquea debido a necesidades de recursos, todos los demás Goroutines se asignan a un nuevo hilo de sistema operativo. Todos estos detalles están ocultos para el programador.

Goroutine anónima

En el lenguaje Go, también puedes arrancar Goroutines para funciones anónimas, es decir, puedes crear una Goroutine anónima simplemente utilizando la palabra clave go como prefijo de la función, como se muestra en la siguiente sintaxis:

Sintaxis:

//Llamada a función anónima
go func (lista_de_parámetros){
    // Sentencia
}(argumentos)
package main 
  
import ( 
    "fmt"
    "time"
) 
  
func main() { 
  
    fmt.Println("¡Bienvenido!! a la función principal") 
  
    //Crear Goroutine anónima
    go func() { 
  
        fmt.Println("¡Bienvenido!! a oldtoolbag.com) 
    }) 
  
    time.Sleep(1 * time.Second) 
    fmt.Println("¡Adiós!! a la función principal") 
}

Salida:

¡Bienvenido!! a la función principal
¡Bienvenido!! a oldtoolbag.com
¡Adiós!! a la función principal