在此,我有一个<代码>sqlite>>
,以确保这些线索在不同的处理器上工作,例如:QSql
。 我有几条镜子,每条处理这个共同数据库的一个不同表格。 我使用<条码>Win AP
SetThreadAffinityMask (hThread, processorMask);
When there s only thread handling one table, it takes 10 seconds and uses 25% of total CPU. But when there re 4 threads handling 4 different tables, it takes nearly 40 seconds and uses only 35% of total CPU. I think the reason is there s some kind of thread-safe
sync in one database. But due to different thread reading or writing different table, thread-safe slows my program. How can I optimize it.
<>Update: 最可能的原因是<代码>Qt或/andSqlite 3
上的一些锁。 我的方案进展缓慢,因此有可能通过预先设定而关闭或绕过这些锁。
<><>Update2: 这里就是一个例子。 (5月稍长,令人不安)
class MultiProcessorThread
{
public:
virtual void run();
bool start()
{
m_hThread = CreateThread (NULL, 0, MultiProcessorThread::ThreadFunc, this, CREATE_SUSPENDED, NULL);
if (m_hThread != INVALID_HANDLE_VALUE)
{
RunningThreadCount++;
m_ProcessorMask = 1 << ( (RunningThreadCount - 1) % ProcessorCount);
SetThreadAffinityMask (m_hThread, m_ProcessorMask); // Make thread working on different processor
ResumeThread (m_hThread);
return true;
}
else
return false;
}
protected:
static DWORD WINAPI ThreadFunc (LPVOID in);
HANDLE m_hThread;
DWORD_PTR m_ProcessorMask;
static DWORD_PTR ProcessorCount;
static DWORD_PTR RunningThreadCount;
static DWORD_PTR GetNumCPUs();
};
DWORD_PTR MultiProcessorThread::ProcessorCount = GetNumCPUs();
DWORD_PTR MultiProcessorThread::RunningThreadCount = 0;
DWORD_PTR MultiProcessorThread::GetNumCPUs() // Get how many processors on this PC
{
SYSTEM_INFO m_si = {0};
GetSystemInfo (&m_si);
return (DWORD_PTR) m_si.dwNumberOfProcessors;
}
DWORD WINAPI MultiProcessorThread::ThreadFunc (LPVOID in)
{
static_cast<MultiProcessorThread*> (in)->run();
return 0;
}
class Run : public MultiProcessorThread
{
public:
void run()
{
int i = 0;
QString add = "insert into %1 values(1)";
add = add.arg (table);
QString sel = "select a from %1 ";
sel = sel.arg (table);
QString del = "delete from %1 where a=1";
del = del.arg (table);
while (++i) // read and write database
{
query.exec (add);
query.exec (sel);
query.exec (del);
}
}
QSqlQuery query;
QString table;
};
int main (int argc, char *argv[])
{
QCoreApplication a (argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase ("QSQLITE", "test");
db.setDatabaseName (":memory:"); // All threads working on the same memory database.
db.open();
QSqlQuery q (db), q1 (db), q2 (db);
q.exec ("create table A (a)");
q1.exec ("create table B (a)");
q2.exec ("create table C (a)"); // All threads working on different table.
Run b[3];
b[0].query = QSqlQuery (q);
b[0].table = "A";
b[1].query = QSqlQuery (q1);
b[1].table = "B";
b[2].query = QSqlQuery (q2);
b[2].table = "C";
b[0].start();
b[1].start();
b[2].start();
return a.exec();
}