多執行緒同步的開發

CalmReason發表於2016-03-29

介紹

根據多執行緒同步原理中介紹的內容可知,多執行緒開發就是要讓多個執行緒正確的訪問臨界資源,實現多執行緒同步

所以,一般的同步策略最簡單的就是:使用互斥體(mutex)來管理臨界資源(與臨界資源同時定義,生命期相同,作用域相同),互斥體提供P、V操作(獲取,獲取不到就等待;釋放,喚醒等待的執行緒)。不同的執行緒使用鎖(Guard)自動呼叫(建構函式、解構函式)互斥體的P、V操作,從而實現同步

互斥體(Mutex)

下面以ACE中互斥體的使用來實現:多個人使用印表機的場景

#include <iostream>
#include "ace/Log_Msg.h"
#include "ace/Mutex.h"
#include "ace/Task.h"

class Printer
{
public:
	Printer(){}
	void print(int paper_id)
	{
		this->mutex_.acquire();
		ACE_DEBUG((LM_DEBUG,"person(%t) is printing paper(%d)\n",paper_id));
		ACE_OS::sleep(1);
		this->mutex_.release();
	}
private:
	ACE_Thread_Mutex mutex_;
};

class Person : public ACE_Task_Base
{
public:
	Person(Printer& printer):printer_(printer){}
	virtual int svc(void)
	{
		ACE_DEBUG((LM_DEBUG,ACE_TEXT("Person(%t) is running\n"))); 
		for (int i=0;i<4;++i)
		{
			this->printer_.print(i);
		}
		return 0;
	}
private:
	Printer& printer_;
};

int main(int argc, char *argv[])
{
	Printer printer_obj;
	Person person1(printer_obj);
	Person person2(printer_obj);

	person1.activate();
	person2.activate();

	person1.wait();
	person1.wait();

	return 0;
}

鎖(守衛、Guard)

Guard類的主要邏輯是建構函式通過執行互斥體的P操作獲取臨界資源;解構函式通過執行互斥體的V操作來釋放臨界資源。在建構函式之後操作臨界資源。構造與析構之間的程式碼段形成臨界區(臨界區越小越好)。

Guard類的原始碼片段:

template <class LOCK>
class Guard
{
public:
	//隱式的切自動的獲取鎖
	ACE_Guard (LOCK &lock): lock_(&lock){acquire();}
	//隱式的釋放鎖
	~ACE_Guard (void){release();}
	//顯示的獲取鎖
	int acquire (void){return owner_ = lock_->acquire();}
	//顯示的釋放鎖
	int release (void)
	{
		if (owner_ == -1)
		{
			return -1;
		} 
		else
		{
			owner_ = -1;
			return lock_->release();
		}
	}

	bool locked (void) const {return owner_ != -1;}

protected:

	//用子類來儲存指標
	ACE_Guard (LOCK *lock): lock_ (lock), owner_ (0) {}
	//指向我們正在看守的LOCK
	LOCK *lock_;
	//跟蹤記錄我們是否獲取了鎖
	int owner_;
};
下面以ACE中的Guard來實現:多個人使用印表機的場景(僅僅改動了印表機列印的同步程式碼)
#include <iostream>
#include "ace/Log_Msg.h"
#include "ace/Mutex.h"
#include "ace/Task.h"

class Printer
{
public:
	Printer(){}
	void print(int paper_id)
	{
		ACE_Guard<ACE_Thread_Mutex> guard(this->mutex_);
		//this->mutex_.acquire();
		ACE_DEBUG((LM_DEBUG,"person(%t) is printing paper(%d)\n",paper_id));
		ACE_OS::sleep(1);
		//this->mutex_.release();
	}
private:
	ACE_Thread_Mutex mutex_;
};

class Person : public ACE_Task_Base
{
public:
	Person(Printer& printer):printer_(printer){}
	virtual int svc(void)
	{
		ACE_DEBUG((LM_DEBUG,ACE_TEXT("Person(%t) is running\n"))); 
		for (int i=0;i<4;++i)
		{
			this->printer_.print(i);
		}
		return 0;
	}
private:
	Printer& printer_;
};

int main(int argc, char *argv[])
{
	Printer printer_obj;
	Person person1(printer_obj);
	Person person2(printer_obj);

	person1.activate();
	person2.activate();

	person1.wait();
	person1.wait();

	return 0;
}

其他庫

(std、boost等基本介面都是如此,可以觸類旁通)



相關文章