golang並發編程實踐 -- 簡單生產者消費者(with lock)

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

上一篇文章用golang中的channel實現了簡單的消費者模型,下面的版本是用傳統的鎖技術實現的版本,相對比會發現golang提供的channel更好用。而且golang的channel可以完成很多在別的語言裡需要很多代碼才能實現的功能。以後陸續解答。

package mainimport ("fmt""sync""time")type Queue struct {Elem     []intCapacity intFront    intRear     intLock     sync.LockerCond     *sync.Cond}func New() *Queue {theQueue := &Queue{}theQueue.Capacity = 10theQueue.Elem = make([]int, 10)theQueue.Front, theQueue.Rear = 0, 0theQueue.Lock = &sync.Mutex{}theQueue.Cond = sync.NewCond(theQueue.Lock)return theQueue}func (self *Queue) Put(e int) {self.Cond.L.Lock()// the Queue is full, Producer waits here// note that we use for not if to test the conditionfor self.Full() {self.Cond.Wait()}self.Elem[self.Rear] = eself.Rear = (self.Rear + 1) % self.Capacityself.Cond.Signal()defer self.Cond.L.Unlock()}func (self *Queue) Get() int {self.Cond.L.Lock()// the Queue is empty, Consumer waits here// note that we use for not if to test the conditionfor self.Empty() {self.Cond.Wait()}p := self.Elem[self.Front]self.Front = (self.Front + 1) % self.Capacityself.Cond.Signal()defer self.Cond.L.Unlock()return p}func (self *Queue) Empty() bool {if self.Front == self.Rear {return true}return false}func (self *Queue) Full() bool {if ((self.Rear + 1) % self.Capacity) == self.Front {return true}return false}func main() {theQueue := New()// producer putsgo func() {for i := 1; i <= 100; i++ {time.Sleep(100 * time.Millisecond)theQueue.Put(i)fmt.Println("Bob puts ", i)}}()// consumer getsfor i := 1; i <= 100; i++ {time.Sleep(100 * time.Millisecond)p := theQueue.Get()fmt.Println("Alice gets : ", p)}}

運行效果如下:

Bob puts  1Alice gets :  1Bob puts  2Alice gets :  2Bob puts  3Alice gets :  3Bob puts  4Alice gets :  4Bob puts  5Alice gets :  5Bob puts  6Alice gets :  6Bob puts  7Alice gets :  7Bob puts  8Alice gets :  8Bob puts  9Alice gets :  9Bob puts  10Alice gets :  10Bob puts  11Alice gets :  11Bob puts  12Alice gets :  12Bob puts  13Alice gets :  13

.......

如此反覆直到100次。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.