Search code examples
c++multithreading

Calling function from different threads is blocking?


I have a class Animal

    class Animal
    {
        public:

            int operator()(const int n=4)
            {
                // do something that takes a while(~1 ms)
                return n*5;
            }
    };

If I spawn off two threads that each have access to one instance of Animal, will the function calls be run in parallel? Or does the second thread have to wait for the first one to finish?

To be more specific, inside each thread I have a pointer to the same Animal instance and inside the thread I call (*pointer_to_animal)(10);

I understand that there my be race conditions when accessing data from both threads, but since all of the variables used inside the function are passed in or created on the stack, there are no race conditions. I'd like the two threads to run in parallel for the same Animal instance.


Solution

  • Yes, unless that function does something (e.g., hold a mutex) to prevent parallel execution, it's entirely possible for it to execute in multiple threads simultaneously.