下面這樣就可以作一個 mutex
#include "ace/Thread_Mutex.h"
ACE_Thread_Mutex mutex1; // 創建互斥鎖1
void Send1(string data)
{
mutex1.acquire(); // 獲得互斥鎖1
// 做一些需要獲得互斥鎖1保護的操作,如 peer().send() 的動作
mutex1.release(); // 釋放互斥鎖1
}
如果有多個 thread同時用這個Send1就不會發生send到一半又有人進來, 同時有二個人使用這個Send1就會發生送出去的資料混在一起,那如果有二個socket要send呢? 用直覺得解法就可以用二個mutex,如下
#include "ace/Thread_Mutex.h"
ACE_Thread_Mutex mutex1; // 創建互斥鎖1
ACE_Thread_Mutex mutex2; // 創建互斥鎖2
void Send1(string data)
{
mutex1.acquire(); // 獲得互斥鎖1
// 做一些需要獲得互斥鎖1保護的操作,如 A.peer().send() 的動作
mutex1.release(); // 釋放互斥鎖1
}
void Send2(string data)
{
mutex2.acquire(); // 獲得互斥鎖2
// 做一些需要獲得互斥鎖2保護的操作,如 B.peer().send() 的動作
mutex2.release(); // 釋放互斥鎖2
}