Search code examples
c++multithreadingthread-safetystdthread

C++ std::threads interacting although they should not


let me appologize in advance for being so vague about the problem. I can not share any details. It is a computer vision problem and a bunch of images are scanned and processed in main(). Every 100 (or so) frames the main() function spawns another thread, which scans the images in a different way (but the first step was requires).

#include <thread>
...

void myFunction(ImageVector, arg2, arg3)
{
    for (i = 0; i < ImageVector.size < ++i)
    {
        process(ImageVector[i])
    }
}

int main(void)
{

std::vector<std::string> images; // paths to the images, please consider it filled somehow, e.g. multiple push_backs



for (i = 0; i < Images.size ; ++i)
     {
         Scan(Images[i]). // Scans the image
         Process(Images[i]) // Processes the image

         if (Something)
         {
            std::vector<std::string> ImageVector(&Images[10], &Images[100]);

            //Spawn the tread and put it into a vector.
            MyThreads.push_back(std::thread(myFunction, ImageVector, arg2, arg3));
         }

     }

     MyThreads[0].join(); // assuming only the first one is filled

}

The images are not the same and read from disk. Nevertheless I checked the reading logic and that is not the problem. If I execute the tasks after another, it works fine. Neither ImageVector, arg2, arg3 are pointers. They are just copies of variables.

Functions myFunction(), Scan(), Process() use similar code-pieces but none of these pieces has shared variables in them. There is also no malloc() as I was told this is not threadsafe, just "new" now.

I realize it is not much to go on but maybe I just forgot something simple.

Thank you

PS: I switched the threading library to boost with no effect,´.


Solution

  • If a program works with no threading and not working with threading then likely reason could be the synchronization. In this specific case, with limited problem description and code snippet available, may be sync issue when accessing ImageVector.