美文网首页
GoLang并发编程3

GoLang并发编程3

作者: 同人于野_2068 | 来源:发表于2019-04-26 17:00 被阅读0次

    并发编程有两个模式

    • 共享内存
    • 消息

    共享内存,以C语言举例

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    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

          本文链接:https://www.haomeiwen.com/subject/sevfnqtx.html