Okay, i've searched the almighty google for some clear answear that would fit my problem but I was unsuccessfull. I'm developing an hardware abstraction layer in C++ that communicates via various serial protocols (SPI, I2C, UART), and I got a lot of ICs on the board that need controlling. Every IC gets it's own class. Since i'm modeling the hardware through classes, I think it's important for me to have the same ammount of instances in my code as the number of ICs mounted on the board. Here's my problem: I need to control the creation of these instances. The solution I came up with was to store the intances in a static std::map, which has a std::string as key (I use the device name for SPI, and the address for I2C for example). The code goes something like this:
IC.h
class SomeICMap { private: static std::map<std::string addr, std::shared_ptr<IC> > instance_map; public: static IC* getInitializedInstance(std::shared_ptr<CommInterface> comm, const std::string& addr); } IC.cpp
std::map<std::string addr, std::shared_ptr<IC> > instance_map; IC* SomeICMap::getInitializedInstance(std::shared_ptr<CommInterface> comm, const std::string& addr) { std::map<string, std::shared_ptr<IC> >::iterator it; it = instance_map.find(addr); if (it == instance_map.end()) { std::shared_ptr<IC> device(new IC(comm, addr)); if (device->init() != 0) { return NULL; } instance_map[addr] = device; return device.get(); } return it->second.get(); } This way I don't get duplicated instances of the hardware that is mounted on the board. I did this for every IC.
My question is: Is this thread safe?
I'm going to use some of these ICs in multiple threads running under Linux. I'm not sure if this is going to be safe, since I'm accesing an static map to get the pointers and access the hardware. From what I read online, the actual access to the hardware is safe, since the kernel takes care of concurrency when using write() read() to manipulate the open file descriptor. What I'm worried about is race conditions to occurr when the program first creates the IC instances.