Attempt to set max concurrent connections manually
This commit is contained in:
parent
b618bf0932
commit
c97454e828
@ -17,6 +17,7 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
@ -26,8 +27,11 @@
|
||||
#include <QString>
|
||||
|
||||
// get_thread_connection and init_database
|
||||
constexpr int MAX_CONNECTIONS = 5;
|
||||
static std::mutex connection_mutex_;
|
||||
static std::condition_variable connection_cv_;
|
||||
static std::atomic<unsigned int> thread_id_counter{1};
|
||||
static int active_connections = 0;
|
||||
static QString shared_database_path;
|
||||
|
||||
static int get_delay(int attempt) {
|
||||
@ -40,7 +44,13 @@ QSqlDatabase get_thread_connection() {
|
||||
bool passed = false;
|
||||
int attempt = 0;
|
||||
while (!passed) {
|
||||
std::lock_guard<std::mutex> lock(connection_mutex_);
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(connection_mutex_);
|
||||
connection_cv_.wait(lock, [] { return active_connections < MAX_CONNECTIONS; });
|
||||
active_connections++;
|
||||
}
|
||||
|
||||
try {
|
||||
thread_local unsigned int thread_unique_id = thread_id_counter.fetch_add(1);
|
||||
connection_name = QString("CIConn_%1").arg(thread_unique_id);
|
||||
|
||||
@ -66,7 +76,21 @@ QSqlDatabase get_thread_connection() {
|
||||
|
||||
if (!thread_db.open()) throw std::runtime_error("Failed to open new database connection for thread: " + thread_db.lastError().text().toStdString());
|
||||
passed = true;
|
||||
} catch (...) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(connection_mutex_);
|
||||
active_connections--;
|
||||
}
|
||||
connection_cv_.notify_one();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(connection_mutex_);
|
||||
active_connections--;
|
||||
}
|
||||
connection_cv_.notify_one();
|
||||
|
||||
return thread_db;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user