diff --git a/SqliteWAL/main.cc b/SqliteWAL/main.cc index 303ad15..8a29d9d 100644 --- a/SqliteWAL/main.cc +++ b/SqliteWAL/main.cc @@ -1,12 +1,50 @@ #include "sqlutils.hpp" #include +#include +#include +#include #include -void insertThread(const QString &brand) +class CountDownLatch +{ + Q_DISABLE_COPY_MOVE(CountDownLatch) +public: + explicit CountDownLatch(int count) + : m_count(count) + {} + void countDown() + { + QMutexLocker lock(&m_mutex); + if (--m_count == 0) { + m_condition.wakeAll(); + } + } + int count() const + { + QMutexLocker lock(&m_mutex); + return m_count; + } + + void wait() + { + QMutexLocker lock(&m_mutex); + while (m_count > 0) { + m_condition.wait(&m_mutex); + } + } + +private: + mutable QMutex m_mutex; + QWaitCondition m_condition; + int m_count; +}; + +void insertThread(const QString &brand, CountDownLatch &countDown) { SqlUtils sqlUtils; + countDown.wait(); for (int i = 0; i < 500; i++) { sqlUtils.insert(brand, i); } @@ -16,15 +54,22 @@ int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); - SqlUtils sqlUtils; + if (!QSqlDatabase::drivers().contains("QSQLITE")) { + qWarning() << "This demo needs the SQLITE driver"; + return -1; + } const QStringList brands{"Apple", "Samsung", "Xiaomi", "Huawei", "Oppo", "Vivo", "Realme"}; + CountDownLatch countDown(1); std::vector threads; for (const auto &brand : brands) { - threads.emplace_back(insertThread, brand); + threads.emplace_back(insertThread, brand, std::ref(countDown)); } + countDown.countDown(); for (auto &thread : threads) { - thread.join(); + if (thread.joinable()) { + thread.join(); + } } return 0; diff --git a/SqliteWAL/sqlutils.cc b/SqliteWAL/sqlutils.cc index 5b635d5..c407317 100644 --- a/SqliteWAL/sqlutils.cc +++ b/SqliteWAL/sqlutils.cc @@ -1,6 +1,5 @@ #include "sqlutils.hpp" -#include #include #include #include @@ -12,24 +11,11 @@ class SqlUtils::SqlUtilsPrivate SqlUtilsPrivate(SqlUtils *q) : q_ptr(q) { - if (checkSQLITEDriver()) { - openSqliteDatabase(); - } + openSqliteDatabase(); } ~SqlUtilsPrivate() { QSqlDatabase::removeDatabase(connectionName); } - bool checkSQLITEDriver() - { - if (QSqlDatabase::drivers().contains("QSQLITE")) { - return true; - } - - qWarning() << "This demo needs the SQLITE driver"; - QMetaObject::invokeMethod(qApp, &QCoreApplication::quit, Qt::QueuedConnection); - return false; - } - void openSqliteDatabase() { s_instanceCount.ref();