【发布时间】:2018-11-27 01:01:46
【问题描述】:
我正在尝试编写一个模拟,其中不同的线程需要根据父线程管理的原子模拟时间对特定于线程的间隔(在此最小示例中,间隔在 1 到 4 之间)执行给定的计算.
这个想法是让父级将模拟推进一个时间步长(在这种情况下,为简单起见,始终为 1),然后让所有线程独立检查它们是否需要进行计算,一旦它们检查完毕,就减少一个原子计数器并等待下一步。我希望在运行此代码后,每个线程的计算次数将恰好是模拟的长度(即 10000 步)除以特定于线程的间隔(因此对于 4 的线程间隔,线程应该执行 exactly 2500 次计算。
#include <thread>
#include <iostream>
#include <atomic>
std::atomic<int> simTime;
std::atomic<int> tocalc;
int end = 10000;
void threadFunction(int n);
int main() {
int nthreads = 4;
std::thread threads[nthreads];
for (int ii = 0; ii < nthreads; ii ++) {
threads[ii] = std::thread(threadFunction, ii+1);
}
simTime = 0;
tocalc = 0;
while (simTime < end) {
tocalc = nthreads - 1;
simTime += 1;
// do calculation
while (tocalc > 0) {
// wait until all the threads have done their calculation
// or at least checked to see if they need to
}
}
for (int ii = 0; ii < nthreads; ii ++) {
threads[ii].join();
}
}
void threadFunction(int n) {
int prev = simTime;
int fix = prev;
int ncalcs = 0;
while (simTime < end) {
if (simTime - prev > 0) {
prev = simTime;
if (simTime - fix >= n) {
// do calculation
ncalcs ++;
fix = simTime;
}
tocalc --;
}
}
std::cout << std::to_string(n)+" {ncalcs} - "+std::to_string(ncalcs)+"\n";
}
但是,输出与预期不一致,一种可能的输出是
2 {ncalcs} - 4992
1 {ncalcs} - 9983
3 {ncalcs} - 3330
4 {ncalcs} - 2448
虽然预期的输出是
2 {ncalcs} - 5000
1 {ncalcs} - 10000
3 {ncalcs} - 3333
4 {ncalcs} - 2500
我想知道是否有人知道为什么这种强制线程等待下一步的方法似乎失败了 - 如果这可能是我的代码的一个简单问题,或者它是一个更基本的问题方法。感谢任何见解,谢谢。
注意
我使用这种方法是因为我尝试过的其他方法的开销(例如,使用pipes,在每个步骤中加入)非常昂贵,如果在我开放的线程之间有一种更便宜的通信方式的话建议。
【问题讨论】:
-
您在主线程中设置了错误的
tocalc,您想等到nthreads减为零,而不是nthreads-1。 -
如果我将行
tocalc = nthreads - 1更改为tocalc = nthreads然后它会无限期挂起,并且主线程的等待循环中的调试语句显示tocalc卡在 1。有什么想法吗? -
在设置为0之前读取simtime的值是多少?
-
您没有足够早地初始化全局变量,并且有多个点无法确保同步。例如,在第一次增加
simTime之前,您需要等待所有线程都设置了它们的prev,否则其中一个线程会卡住。然后在每次迭代中,您需要等待simTime和tocalc都设置好,然后再在线程中进行计算。以此类推。
标签: c++ multithreading optimization simulation thread-synchronization