Home >Backend Development >Golang >How Do I Prevent the Main Goroutine in a Go Program from Terminating Prematurely?

How Do I Prevent the Main Goroutine in a Go Program from Terminating Prematurely?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 18:29:10154browse

How Do I Prevent the Main Goroutine in a Go Program from Terminating Prematurely?

Main Goroutine Persistence in Go Programs

One may encounter the question of how to prevent the main goroutine of a Go program from terminating prematurely. In other words, the goal is to keep the program running indefinitely, except through explicit user intervention.

"Sleeping" the Main Goroutine

There are several approaches to make the main goroutine wait forever without consuming CPU resources:

  • An empty select statement:

    select {}
  • Receiving from an uninitialized channel:

    <-make(chan int)
  • Receiving from a nil channel:

    <-(chan int)(nil)
  • Sending to a nil channel:

    (chan int)(nil) <- 0
  • Locking a locked sync.Mutex:

    mu := sync.Mutex{}
    mu.Lock()
    mu.Lock()

Quitting the Program

If a mechanism to terminate the program is desired, a simple channel can serve the purpose:

var quit = make(chan struct{})

func main() {
    // Startup code...

    // Blocking (waiting for quit signal):
    <-quit
}

// Quitting in another goroutine:
close(quit)

Sleeping without Blocking

An alternative approach to keeping the program running without blocking the main goroutine is to use a long sleep duration:

time.Sleep(time.Duration(1<<63 - 1))

For extremely long-running programs, a loop of such sleeping statements can be employed:

for {
    time.Sleep(time.Duration(1<<63 - 1))
}

The above is the detailed content of How Do I Prevent the Main Goroutine in a Go Program from Terminating Prematurely?. 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