#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *count(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int 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 ); }现在我们尝试将这段C语言代码直接翻译为Go语言代码,代码如下所示。
package main 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 } } }在上面的例子中,我们在 10 个 goroutine 中共享了变量 counter。每个 goroutine 执行完成后,会将 counter 的值加 1。因为 10 个 goroutine 是并发执行的,所以我们还引入了锁,也就是代码中的 lock 变量。每次对 n 的操作,都要先将锁锁住,操作完成后,再将锁打开。
本文链接:http://task.lmcjl.com/news/14341.html