1

For example, I have multi-threaded application which can be presented as:

Data bigData;

void thread1()
{
  workOn(bigData);
}
void thread2()
{
  workOn(bigData);
}
void thread3()
{
  workOn(bigData);
}

There are few threads that are working on data. I could leave it as it is, but the problem is that sometimes (very seldom) data are modified by thread4.

void thread4()
{
  sometimesModifyData(bigData);
}

Critical sections could be added there, but it would make no sense to multi-threading, because only one thread could work on data at the same time.

What is the best method to make it sense multi-threading while making it thread safe?

I am thinking about kind of state (sempahore?), that would prevent reading and writing at the same time but would allow parallel reading.

4

1 に答える 1

1

これは、リーダーライター ロックと呼ばれます。ミューテックスと呼ばれるものを実装して、書き込みが行われているときに誰も読み取らず、読み取りが行われているときに誰も書き込まないようにすることができます。この問題を解決する 1 つの方法は、フラグを設定することです。ライターが何かを変更する必要がある場合は、ロックをオンにします。NO MORE リーダーが読むことができなくなり、現在のすべてのリーダーが終了した後、ライターはその仕事をするようになり、次に再びリーダーが読み取ります。

于 2013-01-08T02:10:02.757 に答える