關於golang的多進程的控制與樣本程式

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

我們寫C 的時候,假如用到多進程,我們通常都會用訊號,管理等來進程進程間的通訊, 那麼golang是怎麼實現這個的呢?? 直接看碼說話吧

package mainimport (  "fmt"  "time")func main() {  timeout := make(chan bool, 1)  go func() {    fmt.Println("------------ 子進程1--------------")    t1 := time.Now().UnixNano()    fmt.Println(t1)    fmt.Println("這個一定會執行")        time.Sleep(3 * time.Second)    // timeout <- true    timeout <- true  }()    fmt.Println("首先邏輯還是響應 main 函數")    go func() {    fmt.Println("------------ 子進程2--------------")    t2 := time.Now().UnixNano()    fmt.Println(t2)    fmt.Println("相當於fork一個子進程在進行")  }()    ch := make(chan int)  select {    case <-ch:    case <-timeout:      fmt.Println("------------ 回到main函數 --------------")      fmt.Println("task is timeout!")  }    fmt.Println("main 函數本身的輸出")}

我們執行代碼看一看結果

首先邏輯還是響應 main 函數------------ 子進程2--------------1471577916141068800相當於fork一個子進程在進行------------ 子進程1--------------1471577916142068800這個一定會執行------------ 回到main函數 --------------task is timeout!main 函數本身的輸出

分別從 納秒的時間戳記可以看出, 兩個 go func() 幾乎是同時執行的, 這種是golang平行處理的寫法, 是直接調用系統的epoll處理流程, golang同樣提供了一種監視手段去監視每個平行處理邏輯的返回, select就是這種手段

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.