From c42695f540acfd2ffaa760ae0ee627d9fe30ca6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=AE=E7=94=9F=E8=8B=A5=E6=A2=A6?= <1070753498@qq.com> Date: Fri, 3 Nov 2023 18:41:09 +0800 Subject: [PATCH] =?UTF-8?q?Modify=20SQLITE=20WAL=20Example=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SqliteWAL/main.cc | 53 +++++++++++++++++++++++++++++++++++++++---- SqliteWAL/sqlutils.cc | 16 +------------ 2 files changed, 50 insertions(+), 19 deletions(-) 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();