简体   繁体   中英

Synchronize access to two matrices

I have n-threads that access to two shared matrices in the following way:

    if (matrix2[i][j] <= d){
        matrix1[i][j] = v;
        matrix2[i][j] = d;
    }

I tried with a unique mutex before the critial section but the performace are very poor. Which is the best way to synchronize this code? A matrix of mutex? Alternatives?

A matrix of mutex?

It's rare for very fine-grained locking to perform better than a smaller number of locks, unless keeping them locked for a long time is unavoidable. That seems unlikely here. It also opens the door to deadlocks (for example, what if one thread runs with i=1, j=2 at the same time as another thread with i=2, j=1 ?).

I tried with a unique mutex before the critical section but the performance are very poor.

What synchronization you need depends on your access pattern. Are multiple threads all performing the operation shown?

If so, do you really need to do that in parallel? It doesn't seem expensive enough to be worthwhile. Can you partition i,j regions between threads so they don't collide? Can you do some other long-running work in your threads, and batch the matrix updates for single-threaded application?

If not, you need to show what other access is causing a data race with the code shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM