写入时违反WaitForMultipleObjects访问

WaitForMultipleObjects access violation when writing

本文关键字:WaitForMultipleObjects 访问      更新时间:2023-10-16

我已经阅读了之前发布的问题,似乎有相同的错误,我在使用等待多个对象时得到,但我相信我的是不同的。我使用几个线程来计算mandelbrot集合的不同部分。程序编译并产生正确的结果大约3/5次,但有时我得到一个错误,说"写入时访问冲突…(一些每次都不同的内存位置)"。就像我说的,有时候有用,有时候没用。我把断点放在waitformultipleobjects的前后,并得出结论,那一定是罪魁祸首。我只是不知道为什么。下面是代码…

int max = size();
if (max == 0)               //Return false if there are no threads
    return false;
for(int i=0;i<max;++i)          //Resume all threads
    ResumeThread(threads[i]);
HANDLE *first = &threads[0];    //Create a pointer to the first thread
WaitForMultipleObjects(max,first,TRUE,INFINITE);//Wait for all threads to finish

更新:我尝试使用for循环和WaitForSingleObject,问题仍然存在。更新2:这是线程函数。这些指针看起来有点难看

unsigned MandelbrotSet::tfcn(void* obj)
{
funcArg *args = (funcArg*) obj;
int count = 0;
vector<int> dummy;
while(args->set->counts.size() <= args->row)
{
        args->set->counts.push_back(dummy);
}
for(int y = 0; y < args->set->nx; ++y)
{
    complex<double> c(args->set->zCorner.real() + (y * args->set->dx), args->set->zCorner.imag() + (args->row * args->set->dy));
    count = args->set->iterate(c);
    args->set->counts[args->row].push_back(count);
}
return 0;
}

解决:好了,大家,我发现问题了。你是对的。它就在线本身。问题是所有的线程都试图将行添加到我的2D计数向量(counts.push_back(dummy))。我猜竞争条件正在生效,每个线程假设它应该添加更多的行,即使它不是必要的。谢谢你的帮助。

我解决了这个问题。我编辑了这个问题并说明了什么是错的,但我将在这里再做一遍。当我试图将复数向量推入线程函数中的2D向量时,我遇到了竞争条件。这是由while循环控制的,当每个线程执行时,每个线程认为它需要将更多的向量推入称为counts的2D向量。我将这个循环移动到构造函数中,并在创建时简单地将所有必要的向量推入计数中。谢谢你帮我换个角度看问题!

相关文章:
  • 没有找到相关文章