GoLang并发编程3

并发编程有两个模式

  • 共享内存
  • 消息

共享内存,以C语言举例

#include 
#include 
#include 

void *count();
// 信号量 互斥锁
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; 
int counter = 0;

main() {
    int rc1, rc2;
    pthread_t thread1, thread2;
  
    /* 创建线程,每个线程独立执行函数functionC */
    if((rc1 = pthread_create(&thread1, NULL, &count, NULL))) {
            printf("Thread creation failed: %d\n", rc1);
    }
    if((rc2 = pthread_create(&thread2, NULL, &count, NULL))) {
            printf("Thread creation failed: %d\n", rc2);
    }
    
    /* 等待所有线程执行完毕 */ 
    pthread_join( thread1, NULL);  
    pthread_join( thread2, NULL);
    exit(0); 
  }

void *count() {
    // 拿到锁
    pthread_mutex_lock( &mutex1 );
    counter++;
    printf("Counter value: %d\n",counter);
    // 释放锁
    pthread_mutex_unlock( &mutex1 );
}

换成 GoLang

  package main
import "fmt" 
import "sync" 
import "runtime"

var counter int = 0

func Count(lock *sync.Mutex) { 
  lock.Lock()
  counter++
  fmt.Println(z)
  lock.Unlock()
}

func main() {
  // 互斥锁
  lock := &sync.Mutex{}
  
  for i := 0; i < 10; i++ {
    go Count(lock)
  }

  for { 
    lock.Lock()
    c := counter
    lock.Unlock()
    runtime.Gosched() 
    if c >= 10 {
      break
    } 
  }
}

你可能感兴趣的:(GoLang并发编程3)