Câu hỏi phỏng vấn Golang
Câu hỏi

List the functions that can stop or suspend the executi...

Câu trả lời

In Go, there are several functions and mechanisms that can stop or suspend the execution of a current goroutine. Here are the primary ones:

  1. time.Sleep():

    • This function pauses the current goroutine for at least the duration specified by the argument passed to it. After the duration elapses, the goroutine wakes up and resumes execution.
    • It is a straightforward way to introduce a delay or a pause in the execution of a goroutine.
    • It does not stop the goroutine permanently; it only suspends its execution temporarily[7].
  2. Channel Operations:

    • Sending or receiving on a channel can suspend a goroutine when the operation cannot proceed immediately. For example, a goroutine blocks when it tries to send data on a channel that is full or when it tries to receive data from an empty channel.
    • Channels are a synchronization primitive that can be used to communicate between goroutines. When a goroutine is waiting on a channel operation, it is effectively suspended until the operation can complete[1][2].
  3. sync.WaitGroup:

    • A WaitGroup waits for a collection of goroutines to finish executing. The method WaitGroup.Wait() blocks the calling goroutine until the counter inside the WaitGroup is decremented to zero, which is typically done by other goroutines calling WaitGroup.Done().
    • This is used for waiting for a set of goroutines to complete rather than suspending a single goroutine[4].
  4. select Statement with a Blocking Case:

    • The select statement allows a goroutine to wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. If none of the cases can proceed, it blocks the goroutine until one can.
    • This is often used in conjunction with channels to wait for an event without busy-waiting[1][2].
  5. runtime.Gosched():

    • This function yields the processor, allowing other goroutines to run. It does not suspend the current goroutine permanently; it simply gives up the CPU time that the goroutine is currently holding, so the scheduler can run other goroutines. Execution of the current goroutine will resume at some point after other goroutines have been given a chance to run[3].
  6. runtime.Goexit():

    • This function terminates the goroutine that calls it. Unlike time.Sleep() or channel operations, Goexit stops the goroutine permanently. Before terminating, it runs any deferred calls in the goroutine. It is different from returning from the main function of the goroutine becau...
senior

senior

Gợi ý câu hỏi phỏng vấn

senior

When is the init() function run?

middle

What are the differences between unbuffered and buffered channels?

expert

How to compare two interfaces in Go?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào