我是一箇中級程序員,但相對多線程的新手。 目前,我正在用類似下面這樣的結構的應用程序:線程安全訪問對象之間共享的數據
class Client
{
public:
Client();
private:
// These are all initialised/populated in the constrcutor.
std::vector<struct clientInfo> otherClientsInfo;
ClientUI* clientUI;
ClientConnector* clientConnector;
}
class ClientUI
{
public:
ClientUI(std::vector<struct clientInfo>* clientsInfo);
private:
// Callback which gets new client information
// from a server and pushes it into the otherClientsInfo vector.
synchClientInfo();
std::vector<struct clientInfo>* otherClientsInfo;
}
class ClientConnector
{
public:
ClientConnector(std::vector<struct clientInfo>* clientsInfo);
private:
connectToClients();
std::vector<struct clientInfo>* otherClientsInfo;
}
有點一個人爲的例子,我知道了。程序流程是這樣的:
客戶端被構造和填充otherClientsInfo並構造clientUI和clientConnector的指針otherClientsInfo。
客戶端隨時調用synchClientInfo()服務器與新客戶端信息進行聯繫,解析新數據並將其推回到其他ClientsInfo或刪除元素。
當connectToClients()被調用但不會改變它們時,clientConnector將訪問otherClientsInfo中的每個元素。
我的第一個問題是,是否我的假設是,如果兩個ClientUI和ClientConnector訪問otherClientsInfo的同時,將程序的炸彈,因爲線程不安全的?
如果是這種情況,那麼我該如何去訪問其他ClientsInfo線程安全的,或許在某個對象訪問它時以某種方式鎖定它?
什麼的線程庫您使用? – hirschhornsalz 2009-10-06 09:43:12
我使用Qt工具包,它調用因爲我在Linux/BSD 所以據我所知並行線程。從其他的答案,我想這也許是好主意 周圍創建矢量一類,也許使用互斥來它 控制訪問。好/壞主意? – Conor 2009-10-06 10:11:35
好主意,像Pete Kirkhams的建議可能會對你最好。 – 2009-10-06 17:38:30