This is a creation in Article, where the information may have evolved or changed.
See Golang Standard Library Sync package provides a traditional mutex, once, cond, Rwmutex, etc. based on shared memory synchronization primitives, just want to write a code experiment.
Type Cond struct {//L is held while observing or changing the condition L Locker//contains filtered O R unexported Fields}
The Cond structure contains an exportable locker object
Func Newcond (l Locker) *cond
The Newcond function accepts an object that implements the locker interface and returns a pointer to cond; pthread_cond_t corresponds to this
Func (c *cond) broadcast ()
Brocast wakes up all the goroutine waiting on this Cond object; Pthread_cond_brocast () corresponds to this
Func (c *cond) Signal ()
Signal wakes a goroutine that is waiting on this cond object again; Pthread_cond_signal () corresponds to this
Type Mutex struct {//contains filtered or unexported fields}
Func (M *mutex) Lock ()
Func (M *mutex) Unlock ()
The Mutex has a Lock,unlock method, so it implements the
Type Locker Interface {Lock () Unlock ()}
#include <stdio.h> #include <pthread.h>pthread_mutex_t mutex = pthread_ mutex_initializer;pthread_cond_t cond = pthread_cond_initializer;int condition = 0;int count = 0;int consume ( void ) { while ( 1 ) { pthread_mutex_lock ( &mutex ); while ( condition == 0 ) pthread_cond_wait ( &cond, &mutex ); printf ( "consumed %d\n", count ); condition = 0; pthread_cond_signal ( &cond ); pthread_mutex_unlock ( &mutex ); } return ( 0 );} Void* produce ( void * arg ) { while ( 1 ) { pthread_mutex_lock ( &mutex ); while ( condition == 1 ) Pthread_cond_wait ( &cond, &mutex ); printf ( " produced %d\n ", count++ ); condition = 1; pthread_cond_signal ( &cond ); pthread_mutex_unlock ( &mutex ); } return ( 0 );} Int main ( void ) { pthread_t thr; pthread_create ( &thr, NULL, &produce, NULL ); &NBSP;&NBSP;&NBSP;RETURN&NBsp;consume ();}
Then the equivalent Golang is implemented:
package main import ( "FMT" "Sync") Var count = 0var condition = 0func main () { lock := new ( Sync. Mutex) cond := sync. Newcond (Lock) go func () { for { lock. Lock () for condition == 0 { cond. Wait () } fmt. Printf ("consumed %d\n", count ) condition = 0 &nbSp; cond. Signal () lock. Unlock () } } () For { lock. Lock () for condition == 1 { cond. Wait () } fmt. Printf ("produced %d\n", count ) count++ condition = 1 cond. Signal () &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;lock. Unlock () }}