Thread-safety of read-only memory access

Posted by Edmund on Stack Overflow See other posts from Stack Overflow or by Edmund
Published on 2010-05-04T04:22:26Z Indexed on 2010/05/04 4:28 UTC
Read the original article Hit count: 234

Filed under:
|
|

I've implemented the Barnes-Hut gravity algorithm in C as follows:

  1. Build a tree of clustered stars.
  2. For each star, traverse the tree and apply the gravitational forces from each applicable node.
  3. Update the star velocities and positions.

Stage 2 is the most expensive stage, and so is implemented in parallel by dividing the set of stars. E.g. with 1000 stars and 2 threads, I have one thread processing the first 500 stars and the second thread processing the second 500.

In practice this works: it speeds the computation by about 30% with two threads on a two-core machine, compared to the non-threaded version. Additionally, it yields the same numerical results as the original non-threaded version.

My concern is that the two threads are accessing the same resource (namely, the tree) simultaneously. I have not added any synchronisation to the thread workers, so it's likely they will attempt to read from the same location at some point. Although access to the tree is strictly read-only I am not 100% sure it's safe. It has worked when I've tested it but I know this is no guarantee of correctness!

Questions

  • Do I need to make a private copy of the tree for each thread?
  • Even if it is safe, are there performance problems of accessing the same memory from multiple threads?

© Stack Overflow or respective owner

Related posts about c

    Related posts about pthreads