我是一个中级程序员,但相对多线程的新手。 目前,我正在用类似下面这样的结构的应用程序:线程安全访问对象之间共享的数据
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