Skip to content

Instantly share code, notes, and snippets.

@FinchPowers
Last active June 23, 2016 14:24
Show Gist options
  • Save FinchPowers/c375a3794a12474231b0ecff09c35998 to your computer and use it in GitHub Desktop.
Save FinchPowers/c375a3794a12474231b0ecff09c35998 to your computer and use it in GitHub Desktop.
mutex connCacheMutex;
map<string, weak_ptr<SftpConnection>> connCache;
std::shared_ptr<SftpConnection> getSftpConnForUri(const std::string & uri)
{
string host = hostnameFromUri(uri);
auto it = connCache.find(host);
if (it != connCache.end()) {
if (auto conn = it->second.lock()) {
return conn;
}
lock_guard<mutex> l(connCacheMutex);
auto conn = make_shared<SftpConnection>();
auto creds = getCredential("sftp", uri);
conn->connectPasswordAuth(hostnameFromUri(uri), creds.id, creds.secret)
it->second = conn;
return conn;
}
// Check again with a lock
lock_guard<mutex> l(connCacheMutex);
it = connCache.find(host);
if (it != connCache.end()) {
if (auto conn = it->second.lock()) {
return conn;
}
}
auto conn = make_shared<SftpConnection>();
auto creds = getCredential("sftp", uri);
conn->connectPasswordAuth(hostnameFromUri(uri), creds.id, creds.secret);
connCache[host] = conn;
return conn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment