Home > Backend Development > Golang > Why Does the Go `time` Package Use an Implementation-less `startTimer` Function?

Why Does the Go `time` Package Use an Implementation-less `startTimer` Function?

DDD
Release: 2024-12-18 17:21:10
Original
204 people have browsed it

Why Does the Go `time` Package Use an Implementation-less `startTimer` Function?

Function call without function body

When browsing through the code of the "time" package to examine the function After(d Duration) <-chan Time, you come across a peculiarity:

func After(d Duration) <-chan Time {
    return NewTimer(d).C
}

func NewTimer(d Duration) *Timer {
    c := make(chan Time, 1)
    t := &Timer{
        C: c,
        r: runtimeTimer{
            when: nano() + int64(d),
            f:    sendTime,
            arg:  c,
        },
    }
    startTimer(&t.r)
    return t
}
Copy after login

The startTimer function doesn't seem to have an implementation own:

func startTimer(*runtimeTimer)
Copy after login

Questions:

  1. Where is the actual code of startTimer?
  2. Why is there an "abstract Method"?
  3. What reasons did the Go developer have for this Design?

Answers:

  1. Location of the actual code:

    The code of startTimer is in the following assembly routine defined:

    //go:linkname startTimer time.startTimer
    // startTimer adds t to the timer heap.
    func startTimer(t *timer) {
        if raceenabled {
            racerelease(unsafe.Pointer(t))
        }
        addtimer(t)
    }
    Copy after login
  2. Abstract methods in Go:

    In Go, function declarations can omit the function body. These declarations only specify the signature of a function implemented outside of Go, e.g. B. as an assembly routine.

  3. Reasons for the design:

    Not all programming languages ​​can fully express their own runtime. Parts of the Go runtime and standard library are written in C, parts in assembler, and others in ".goc", a not comprehensively documented mix of Go and C.

The above is the detailed content of Why Does the Go `time` Package Use an Implementation-less `startTimer` Function?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template