学习,Go 传统共享内存并发示例

对于共享内存中,某共享变量累加。

posix 中的 pthread:

/**
 * Go 语言编程 4-2
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

unsigned counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void * count() {
    pthread_mutex_lock(&mutex);
    counter++;
    printf("%dn", counter);
    pthread_mutex_unlock(&mutex);
}

int main() {
    int stats[10];
    pthread_t threads[10];

    for (int i = 0; i < 10; i++)
        if ( 0 != (stats[i] = pthread_create(&threads[i], NULL, &count, NULL)) )
            printf("Thread creation failed: %dn", stats[i]);

    for (int i = 0; i < 10; i++)
        pthread_join(threads[i], NULL);

    return EXIT_SUCCESS;
}

go 中的等同:

package main

/**
 * Go 语言编程 4-3
 */

import (
    "fmt"
    "runtime"
    "sync"
)

var counter int = 0

func Count(lock *sync.Mutex) {
    lock.Lock()
    counter++
    fmt.Println(counter)
    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
        }
    }
}

参考:

  1. Go 语言编程

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s