互斥鎖(mutex) 通過鎖機制實現線程間的同步。
1、初始化鎖。在Linux下,線程的互斥量數據類型是pthread_mutex_t。在使用前,要對它進行初始化。
2、靜態分配:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
3、動態分配:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *mutexattr);
4、加鎖。對***享資源的訪問,要對互斥量進行加鎖,如果互斥量已經上了鎖,調用線程會阻塞,直到互斥量被解鎖。
int?pthread_mutex_lock(pthread_mutex?*mutex);int?pthread_mutex_trylock(pthread_mutex_t?*mutex);
解鎖。在完成了對***享資源的訪問後,要對互斥量進行解鎖。
int?pthread_mutex_unlock(pthread_mutex_t?*mutex);
銷毀鎖。鎖在是使用完成後,需要進行銷毀以釋放資源。
int?pthread_mutex_destroy(pthread_mutex?*mutex);
#include?<cstdio>?
#include?<cstdlib>?
#include?<unistd.h>?
#include?<pthread.h>?
#include?"iostream"?
using?namespace?std;?
pthread_mutex_t?mutex?=?PTHREAD_MUTEX_INITIALIZER;?
int?tmp;?
void*?thread(void?*arg)?
{?
cout?<<?"thread?id?is?"?<<?pthread_self()?<<?endl;?
pthread_mutex_lock(&mutex);?
tmp?=?12;?
cout?<<?"Now?a?is?"?<<?tmp?<<?endl;?
pthread_mutex_unlock(&mutex);?
return?NULL;?
}?
int?main()?
{?
pthread_t?id;?
cout?<<?"main?thread?id?is?"?<<?pthread_self()?<<?endl;?
tmp?=?3;?
cout?<<?"In?main?func?tmp?=?"?<<?tmp?<<?endl;?
if?(!pthread_create(&id,?NULL,?thread,?NULL))?
{?
cout?<<?"Create?thread?success!"?<<?endl;?
}?
else?
{?
cout?<<?"Create?thread?failed!"?<<?endl;?
}?
pthread_join(id,?NULL);?
pthread_mutex_destroy(&mutex);?
return?0;?
}?
//編譯:g++?-o?thread?testthread.cpp?-lpthread