http://blog.csdn.net/lzx_bupt/article/details/6913151
最近喜歡聽大學聽到的老歌,deutschland 德國世界盃時候流行的,據說不是主題曲但是比主題曲還要火。
本篇進入痛點了,mutex互斥鎖概念,mutex=mutual exclusion的縮寫,順便說一句:以前老師都愛用縮寫,也不跟同學說全稱,這尼瑪能理解深刻麼!下文是用法:
[cpp] view plaincopy
- #include <iostream>
- #include <pthread.h>//按規矩不能少
-
- using namespace std;
-
- #define NUM_THREADS 5
-
- int sum = 0;//定義個全域變數,讓所有線程進行訪問,這樣就會出現同時寫的情況,勢必會需要鎖機制;
- pthread_mutex_t sum_mutex;
-
- void* say_hello(void* args)
- {
- cout << "hello in thread " << *((int *)args) << endl;
- pthread_mutex_lock (&sum_mutex);//修改sum就先加鎖,鎖被佔用就阻塞,直到拿到鎖再修改sum;
- cout << "before sum is " << sum << " in thread " << *((int *)args) << endl;
- sum += *((int *)args);
- cout << "after sum is " << sum << " in thread " << *((int *)args) << endl;
- pthread_mutex_unlock (&sum_mutex);//完事後解鎖,釋放給其他線程使用;
-
- pthread_exit(0);//退出隨便扔個狀態代碼
- }
-
- int main()
- {
- pthread_t tids[NUM_THREADS];
- int indexes[NUM_THREADS];
- //下三句是設定線程參數沒啥可說的
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
- pthread_mutex_init (&sum_mutex, NULL);//這句是對鎖進行初始化,必須的;
-
- for(int i = 0; i < NUM_THREADS; ++i)
- {
- indexes[i] = i;
- int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//5個進程去你們去修改sum吧哈哈;
- if (ret != 0)
- {
- cout << "pthread_create error: error_code=" << ret << endl;
- }
- }
-
- pthread_attr_destroy(&attr);//刪除參數變數
-
- void *status;
- for (int i = 0; i < NUM_THREADS; ++i)
- {
- int ret = pthread_join(tids[i], &status);
- if (ret != 0)
- {
- cout << "pthread_join error: error_code=" << ret << endl;
- }
- }
-
- cout << "finally sum is " << sum << endl;
-
- pthread_mutex_destroy(&sum_mutex);//登出鎖,可以看出使用pthread內建變數神馬的都對應了銷毀函數,估計是記憶體泄露相關的吧;
- }
慣例:g++ -lpthread -o ex_mutex ex_mutex.cpp
運行:
[cpp] view plaincopy
- hello in thread 4
- before sum is 0 in thread 4
- after sum is 4 in thread 4
- hello in thread 3
- before sum is 4 in thread 3
- after sum is 7 in thread 3
- hello in thread 2
- before sum is 7 in thread 2
- after sum is 9 in thread 2
- hello in thread 1
- before sum is 9 in thread 1
- after sum is 10 in thread 1
- hello in thread 0
- before sum is 10 in thread 0
- after sum is 10 in thread 0
- finally sum is 10
發現個現象,thread4先運行,很詭異吧而i是從0遞增的,所以呢多線程的順序是混亂的,混亂就是正常;只要sum訪問及修改是正常的,就達到多線程的目的了,運行順序不能作為參照;