Skip to content

Commit

Permalink
Modify SQLITE WAL Example;
Browse files Browse the repository at this point in the history
  • Loading branch information
RealChuan committed Nov 3, 2023
1 parent 77447c0 commit c42695f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 19 deletions.
53 changes: 49 additions & 4 deletions SqliteWAL/main.cc
Original file line number Diff line number Diff line change
@@ -1,12 +1,50 @@
#include "sqlutils.hpp"

#include <QCoreApplication>
#include <QMutex>
#include <QSqlDatabase>
#include <QWaitCondition>

#include <thread>

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);
}
Expand All @@ -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<std::thread> 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;
Expand Down
16 changes: 1 addition & 15 deletions SqliteWAL/sqlutils.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#include "sqlutils.hpp"

#include <QCoreApplication>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
Expand All @@ -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();
Expand Down

0 comments on commit c42695f

Please sign in to comment.