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
Release: 2024-12-13 18:29:10
Original
145 people have browsed it

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 {}
    Copy after login
  • Receiving from an uninitialized channel:

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

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

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

    mu := sync.Mutex{}
    mu.Lock()
    mu.Lock()
    Copy after login

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

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

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

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

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template