问题
I have a problem with my code which is that the result between multi-threading and single-threaded are different.
I have a function which takes an input image, and rotates in n steps around the center, and does some analysis on that image. To increase the speed of that, I rewrote the function to take as input the start angle, and end angle, and it calculates the values in between.
Prototype is
void rotateImageConvolution(float* image, int startMin, int startMax)
Now when I call that function with 0..180, it will return the same result every single time, which works fine. Since I have a 4 core CPU, I have 3 threads running, going 0..60, 60..120, 120..180, since it goes (int i = startMin; i < startMax)
The only write to global memory is
if(convolution_image[i] < convrst)
{
WaitForSingleObject( mLock[i], // handle to mutex
INFINITE); // no time-out interval
if(convolution_image[i] < convrst)
{
convolution_image[i] = convrst;
r_map_image[i] = (unsigned char)r0;
orientation_map_image[i] = (unsigned char)a;
}
ReleaseMutex(mLock[i]);
}
where convrst is the result of the convolution, and the convolution_image saves the calculated values. i is the index in the image and goes 0..imagesize mLock is a block of handles
mLock = new HANDLE[imgsize];
for(int i = 0; i < imgsize; ++i)
{
mLock[i] = CreateMutex( NULL, FALSE, NULL);
}
all other memory used is allocated in the function and freed again. The funny thing is, if I disable the Mutex in the convrst part, I get random results, a lot of different ones. If I enable them, I get one of two results, one being the correct result (the same as the single threaded), and half the time a different one.
I cannot figure out what is happening here, and can't see what's going wrong there.
What could be the issue?
回答1:
What if your mutex wraps the entire if statement? Keep in mind that your if statement may be reading in convolution_image[i] while another thread is in the middle of writing it.
The scenario that may be tripping you up:
- Thread 1 just finishes locking the critical section
- Thread 2 then evaluates the if statement.
- Thread 2 is then blocked by the mutex
- Thread 1 unlocks the mutex (and by implication, has calculated convolution_image[i]).
- Thread 2 then locks the critical section, and then goes and calculates the same convolution_image[i] as thread 1 did in step #4.
来源:https://stackoverflow.com/questions/11292091/multithreaded-returns-different-result-from-single-threaded