[英]Multiple Threads of C++ application block each other while (de-)allocating memory
世界,
我嘗試運行具有多個線程的 C++ 應用程序(在 VS 中編譯為 .exe),並為此使用 QThread 或 omp-parallelization。 在使用 umfpack 求解從這些矩陣構建的方程系統之前,每個線程都會執行多次內存分配/解除分配以執行大型矩陣計算。 現在,當我使用太多線程時,我會降低性能,因為線程在執行此操作時會相互阻塞。 我已經讀過內存(取消)分配一次只能用於一個線程(如互斥條件)。
我已經嘗試過的:
在我的設置中,我可以在性能下降之前使用 ~4 個線程(每個線程使用 ~1.5 GB RAM)。 有趣的是——但我還無法理解——只有在幾個線程完成並且新線程接管之后,性能才會降低。 另請注意,線程彼此不依賴,沒有其他阻塞條件,每個線程運行的時間大致相同(~2 分鍾)。
有沒有一種“簡單的方法”——例如以某種方式設置堆/堆棧——來解決這個問題?
以下是一些代碼片段:
// Loop to start threads
forever
{
if (sem.tryAcquire(1)) {
QThread *t = new QThread();
connect(t, SIGNAL(started()), aktBer, SLOT(doWork()));
connect(aktBer, SIGNAL(workFinished()), t, SLOT(quit()));
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
aktBer->moveToThread(t);
t->start();
sleep(1);
}
else {
//... wait for threads to end before starting new ones
//... eventually break
}
qApp->processEvents();
}
void doWork() {
// Do initial matrix stuff...
// Initializing array pointers for umfpack-lib
static int *Ap=0;
static int *Ai=0;
static int *Ax=0;
static int *x=0;
static int *b=0;
// Private static Variablen per thread
#pragma omp threadprivate(Ap, Ai, Acol, Arow)
// Solving -> this is the part where the threads block each other, note, that
there are other functions with matrix operations, which also (de-)/allocate a
lot
status = umfpack_di_solve (UMFPACK_A, Ap,Ai,Ax,x,b, /*...*/);
emit(workFinished());
}
對於那些對我的解決方案感興趣的人:我在我的應用程序中包含了另一個分配器(正如@Ben Voigt 建議的那樣)。 就我而言,我選擇了 mimalloc,因為它似乎得到了定期維護(甚至由 microsoft 本身)並且可以很容易地包含在內。 見這里: Mimalloc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.