I have read articles about double-check which may not be safe with C++ on arbitrary CPU. I am not quite sure whether my codes are absolutely safe or not. Class Database represents database file, and the connection is dynamically created when needed. Database::GetConnection may be called from different threads simultaneously. If the code is not absolutely safe, how can I modify the code. Thank you.
#include <mutex>
#include "sqlite3.h"
class Connection
{
private:
sqlite3* _handle;
std::string _path;
public:
Connection(const std::string& path) : _path(path) {
sqlite3_open(_path.c_str(), &_handle);
// some other initialization work..
}
}
class Database
{
private:
typedef enum
{
Void,
Connected,
// some other status...
} Status;
std::string _path;
std::mutex _mutex;
Status _status;
Connection* _connection;
void OpenDatabase()
{
_connection = new Connection(_path);
_status = Connected;
}
public:
Connection* GetConnection()
{
if (_status == Connected)
return _connection;
std::lock_guard<std::mutex> guard(_mutex);
if (_status != Connected)
OpenDatabase();
return _connection;
}
public:
Database(const std::string& path) : _path(path), _status(Void) {};
};