Ali Kavis
Ali Kavis

Reputation: 13

How do two or more std::threads operate on the same function?

I am developing a C++ program in which I am processing several pairs of data(arrays and matrices). Due to time requirements, I need to process corresponding pairs in parallel and I am planning to use std::threads for that purpose. Since they will be calling the same function, I need to make sure that they never mess with each others' operations.

I would like to know whether each thread creates its own call stack and local function variables for the same function called by different threads are unique to the caller.

Also, all the threads need to write to different parts of the same output array. Will it cause a problem even if they are not writing to the same portion of the array?

Upvotes: 1

Views: 1131

Answers (1)

Markus Mayr
Markus Mayr

Reputation: 4118

You're fine.

Each thread has its own stack and when two threads write to or read from different memory locations, there are no race conditions.

Potential pitfalls in your case would be:

  • Your function writes to global variables.
  • Your function gets parameters by reference and mutates them.
  • There are locations in your output array that are accessed by both threads.

As a side note, if parallelization is that simple, it can be interesting to take a look at OpenMP or stuff like that that makes that kind of parallelization fairly simple.

Upvotes: 2

Related Questions