1
votes

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.

1

1 Answers

1
votes

This is called a readers–writer lock. You could implement what is called a mutex to make sure no one reads when write is going on and no one writes when reads are going on. One way to solve the problem would be to have flags. If the writer is got something to modify, then switch on a lock. Upon which NO MORE readers will get to read and after all the current readers have finished, the writer will get to do its job and then again the readers read.