標籤:
談到多線程編程,同步是一定要講的。給個例子:
#include <stdio.h>#include <stdlib.h>#include <pthread.h>int count = 0;#define N 100000void* fun(){ int i; for (i = 0; i < N; ++i) { int tmp = count; tmp++; count = tmp; }}int main(){ pthread_t tid1, tid2; int ret1, ret2; ret1 = pthread_create(&tid1, NULL, fun, NULL); ret2 = pthread_create(&tid2, NULL, fun, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); printf("count = %d\n", count); return 0;}View Code
兩個線程同時對一個資料執行自增操作,結果是多少呢?
可以看出,每次執行的結果都是不一樣的。而且,都不是我們所希望的200000。主要原因是程式裡的自增操作不是原子操作,兩個線程由於CPU的調度,會交錯執行。
接下來,我們通過互斥量來實現兩個線程的同步。
#include <stdio.h>#include <stdlib.h>#include <pthread.h>int count = 0;#define N 100000pthread_mutex_t mutex;void* fun(){ int i; for (i = 0; i < N; ++i) { pthread_mutex_lock(&mutex); int tmp = count; tmp++; count = tmp; pthread_mutex_unlock(&mutex); }}int main(){ pthread_mutex_init(&mutex, NULL); pthread_t tid1, tid2; int ret1, ret2; ret1 = pthread_create(&tid1, NULL, fun, NULL); ret2 = pthread_create(&tid2, NULL, fun, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); printf("count = %d\n", count); pthread_mutex_destroy(&mutex); return 0;}View Code
在自增操作前後,通過成對的加鎖解鎖操作,使得自增操作成為一個原子操作,從而達到線程同步。
多線程同步