Multithreaded returns different result from single threaded

若如初见. 提交于 2019-12-25 04:05:55

问题


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:

  1. Thread 1 just finishes locking the critical section
  2. Thread 2 then evaluates the if statement.
  3. Thread 2 is then blocked by the mutex
  4. Thread 1 unlocks the mutex (and by implication, has calculated convolution_image[i]).
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!