Summary of Golang knowledge points

Source: Internet
Author: User
Tags inheritance mutex
1. When the runtime is set. Gomaxprocs will be better to improve speed.

Go defaults to using a CPU core by setting the runtime. Gomaxprocs can be set to use multi-core, not the more cores processing faster, to set the number of cores according to different business scenarios, such as: suitable for multi-core scenarios: CPU-intensive, high degree of parallelism, such as the majority of the order, complex calculation. Not suitable for setting up multi-core scenarios: IO-intensive, read-write files, crawlers if you just grab a webpage and not analyze the scene. 2, Sync. Waitgroup usage

Waitgroup in the Go language, used for thread synchronization, single literal meaning understanding, wait waiting for the meaning, group groups, the meaning of the team, waitgroup means waiting for a group, waiting for a series after the completion of the execution will not continue to execute down. Stick to Google's official code:

Package main

Import (
    "FMT"
    "Sync" "
    net/http"
)

func main () {
    var wg sync. Waitgroup
    var urls = []string{
            "http://www.golang.org/",
            "http://www.google.com/",
            "/HTTP/ www.baiyuxiong.com/",
    }
    for _, url: = range urls {
            //Waitgroup Add a count.
            Wg. ADD (1)
            //Execute Goroutine Crawl Web page.
            Go func (URL string) {
                    //when Goroutine is complete, reduce the count of Waitgroup.
                    Defer WG. Done ()
                    //Fetch the URL.
                    http. Get (URL)
            FMT. Println (URL);
            } (URL)
    }
    Wait for all HTTP to complete.
    Wg. Wait ()
    FMT. Println ("over");
}
#执行结果:
http://www.baiyuxiong.com/
http://www.google.com/
http://www.golang.org/
over

From the results of the implementation can be seen:
1. When you fetch three URL information, the order of the result display is not necessarily related to the order of the For loop.
2, three goroutine all executed after completion, WG. Wait () stops waiting, resumes execution and prints a combination of the over character 3, go language inheritance

Type People struct{}
func (P *people) ShowA () {
    fmt. Println ("ShowA")
    P.showb ()
}
func (P *people) Showb () {
    fmt. Println ("Showb")
}

type Teacher struct {
    people
}
func (t *teacher) Showb () {
    fmt. Println ("Teacher Showb")
}

func main () {
    T: = teacher{}
    t.showa ()
}

This is a combination of golang patterns that enable the inheritance of OOP. The combined type people contains methods that have been upgraded to a method of the teacher of this combination type (must be an anonymous field), but their method (ShowA ()) is called without a change in the recipient. At this point the people type does not know what type of combination it will be, and of course it cannot invoke the function of the unknown combinatorial teacher type when calling the method. 4. Go language Select random Select if one case can return, execute immediately. If more than one case can return at the same time, the pseudo-random method extracts any one execution. If there is not a case to return, you can execute the "default" block. If a single Chan is not buffered, it will block

5. Map Thread Safety
When a thread is unsafe, it may occur: fatal Error:concurrent map read and map write may appear
The following is an example of an unsafe map:

Type userages struct {
    ages map[string]int
    sync. Mutex
}
func (UA *userages) ADD (name string, age int) {
    ua. Lock ()
    defer UA. Unlock ()
    ua.ages[name] = Age
}
func (UA *userages) Get (name string) int {
    If age, OK: = Ua.ages[name]; ok {
        return Age
    }
    return-1
}

The following changes are followed:

Func (UA *userages) Get (name string) int {
    UA. Lock ()
    defer UA. Unlock ()
    if age, OK: = Ua.ages[name]; OK {
        return-age
    }
    return-1
}
5, Sync. Rwmutex and Sync.mutex differences

The Golang Sync package implements two types of lock mutexes (mutexes) and Rwmutex (read and write locks), where Rwmutex is implemented based on mutexes, and read-only locks are implemented using similar functions as reference counters.

    Type Mutex
        func (M *mutex) lock ()
        func (M *mutex) Unlock ()
    type Rwmutex
        func (rw *rwmutex) lock ()
        fun C (RW *rwmutex) rlock ()
        func (rw *rwmutex) rlocker () Locker
        func (rw *rwmutex) runlock ()

        func (rw *rwmutex) Un Lock ()
Where the mutex is a mutex, lock () lock, Unlock () Unlock, use lock () lock, you can not lock it again, until it is unlocked with Unlock (), it can be locked again. For read-write uncertainty scenarios, where there is no obvious difference between read and write times, and only one read or write is allowed, the lock leaf is called a global lock. Rwmutex is a read-write lock that can add multiple read locks or a write lock, which is often used to read far more than the number of writes. Func (rw *rwmutex) lock () write lock, if there are additional read and write locks before the write lock is added, lock blocks until the lock is available, and to ensure that the lock is finally available, the blocked lock call excludes the new reader from the acquired lock, that is, the write lock permission is higher than the read lock. Write lock is preferred when there is a write lock. 6. Type usage


Switch Typevalue. Type) {
Case int:
println (' int ')
Case string:
println (' string ')
Case interface{}:
println ("I Nterface ")
Default:
println (" Unknown ")
}
where typevalue must be interface type 7, defer usage Summary The defer must follow the function. Defer executes before the end of the function, it is possible that the function encounters a panic after the function has completed its normal execution, after the function encounters a return and executes a return. Execution order: function content –return–defer–panic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.