1. 程式人生 > >linux下互斥鎖的使用

linux下互斥鎖的使用

原始碼如下

#include <cstdio>  
#include <cstdlib>  
#include <unistd.h>  
#include "iostream"  
#include <pthread.h>  
using namespace std;  
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  	//初始化 互斥鎖
int tmp;  
void* thread(void *arg)  
{  
	cout << "thread id is " << pthread_self() << endl;  	//列印當前執行緒id
	pthread_mutex_lock(&mutex);  	//加鎖  place1
	tmp = 12;  
	cout << "Now a is " << tmp << endl;  
	sleep(5);
	cout << "Now after a is " << tmp << endl;  
	pthread_mutex_unlock(&mutex);  	//解鎖	place1
	return NULL;  
}  

void* thread2(void *arg)  
{  
	cout << "thread id2 is " << pthread_self() << endl;  	
	pthread_mutex_lock(&mutex);  	//加鎖	place1
	tmp = 22;  
	cout << "Now a is " << tmp << endl;  
	sleep(5);
	cout << "Now after a is " << tmp << endl;  
	pthread_mutex_unlock(&mutex);  	//解鎖	place1
	return NULL;  
}  

int main()  
{  	
	//thread id
	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;  
	} 


	//thread id2
	pthread_t id2;  
	cout << "main thread id is " << pthread_self() << endl;  
	tmp = 13;  
	cout << "In main func tmp = " << tmp << endl;  
	if (!pthread_create(&id2, NULL, thread2, NULL))  
	{  
		cout << "Create thread success!" << endl;  
	}  
	else  
	{  
		cout << "Create thread failed!" << endl;  
	} 

	
	pthread_join(id, NULL);  	//等待一個執行緒的結束。阻塞	place2
	pthread_join(id2, NULL);  	//等待一個執行緒的結束。阻塞	place2
	pthread_mutex_destroy(&mutex);  
	return 0;  
}  

主執行緒起了 id 和id2兩個子執行緒。

按照上述原始碼:

執行結果是,

此時id和id2是同步的。

非同步建立好兩個執行緒,id 和id2,然後主程式阻塞在 pthread_join(id, NULL);

然後id 和id2 隨即(貌似總是id2先) 執行各自的執行緒函式;

由於加鎖了,所以若先執行了id2,則會在id2中一直執行,包括裡面的sleep5s;

5s之後,id2釋放鎖,id拿到鎖,才進入到id的執行緒函式中。

id執行緒函式執行完成後才執行pthread_join的阻塞函式。

一.若只將 4處place1註釋掉。

則此時 id和id2兩個執行緒是非同步的 

非同步建立好兩個執行緒,id 和id2,然後主程式阻塞在 pthread_join(id, NULL);

id和id2同時執行,同時sleep 5s,5s之後,同時離開各自的執行緒函式。

然後進入到thread的阻塞函式中去。

二.若只將 2出place2註釋掉

     main函式建立完兩個執行緒後,也不管子執行緒的工作情況,main函式繼續執行,知道return。

    此時,兩個子函式都還沒有執行完。