开发者

How can threads write into different cells of a matrix

I have a global matrix (type vector< vector< char> > ) and I need several t开发者_如何转开发hreads to be able to write into it in the way I said. At first, I thought about using only one mutex, because I'm afraid about race-condition (access+write may not be atomic) Then I used a matrix of mutexes. I'm not quite sure about this. It's seems to be the same problem.

Can you help me please? I'll add more details if you need. Thanks


You only need a mutex to protect objects that are accessed by more than one thread, where at least one of these threads modifies the object.

If your matrix is resized before any threads access it (e.g. before the threads are started) then you only need a mutex if more than one thread accesses the same cell. If your threads are accessing different cells, then provided none of them resize the matrix everything will be OK.

If one thread writes to a cell and another reads from the same cell, then both threads must lock the same mutex before they access that cell. If two threads write to the same cell then again both threads must lock the same mutex. This can be a different mutex to that used for other cells, or it can be the same one.

If one thread modifies the matrix structure whilst any other threads are accessing the matrix then all threads involved must lock the same mutex. This can be a different mutex to any mutexes used for individual cells, or it can be the same one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜