Skip to content

Instantly share code, notes, and snippets.

@chairco
Last active November 20, 2018 02:29
Show Gist options
  • Save chairco/fd6308c86587a5385eaa6c1b9254b8b6 to your computer and use it in GitHub Desktop.
Save chairco/fd6308c86587a5385eaa6c1b9254b8b6 to your computer and use it in GitHub Desktop.
Goroutine
package main

import "fmt"

func main() {
    a := 0
    times := 10000  // <-- HERE
    c := make(chan bool)

    for i := 0; i < times; i++ {
        go func() {
            a++
            c <- true
        }()
    }

    for i := 0; i < times; i++ {
        <-c
    }
    fmt.Printf("a = %d\n", a)
}

#

package main

import (
  "fmt"
  "sync"
)

func main() {
    a := 0
    times := 10000
    c := make(chan bool)

    var m sync.Mutex

    for i := 0; i < times; i++ {
        go func() {
            m.Lock() // 取得鎖
            a++
            m.Unlock() // 釋放鎖
            c <- true
        }()
    }

    for i := 0; i < times; i++ {
        <-c
    }
    fmt.Printf("a = %d\n", a)
}

無狀態的通訊範例

  1. client send: http://xxx.xxx.com/user/1234?access-key=hello
  2. server 解密 access-key 得到一個 session id=0x1234
  3. server 根據 id 到 redis 資料庫拿回登入狀態並且知道用戶是 1234 且有權限
  4. server 到 postgresql 取資料
  5. server 將資料用 JSON 傳回用戶

atomic

完整執行後的 api 呼叫不能讓 server slid 數據停留在不一致狀態,簡單說就是不要有 dependence 的 api 操作

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment