Amey Jah
Amey Jah

Reputation: 913

Is read-write lock needed for this use-case

My question is similar to this thread, however I am sure if the conclusion drawn in the given thread applies here.

My use case: In the application, there is a status thread which sends out the same texual information after every 1 second. Texual information contains the application group name. This status is used by status reader to determine if application server is on/off.

Now application group name can change during it's life time. It is ensured that only single thread in the application triggers this event due to some user activity. Now this single thread has the new application group name which I need to update to my status thread.

My current implementation is as follows

  1. Status Thread Main() Take ReadLock Read the application group name Release the ReadLock

    send the status

  2. Updater Thread Main() Taken write Lock Update the group name Release the WriteLock

However, due to large number of updates to be sent I fear that I might introduce performance degration for heavy load. So I am working on following implementation, but I am not sure if this would work.

New proposed implementation is

  1. Sender Thread holds char* ptr, char[1024] primaryData, char[1024] secondaryData.
  2. When first time application is started, group name is updated in primaryData and ptr points to primaryData.
  3. Whenever update thread has update event, it will Check if (ptr == primaryData) Copy new application name to secondaryData ptr = secondaryData else Copy new application name to primaryData. ptr = primaryData
  4. Status thread will always use data pointed by ptr to send the status. Status Thread will eventually receive updated ptr (considering cache coherency) and will start transmitting new data.

Few points to be considered over here. 1. It's ok even if new data is not instantly available to Status thread 2. I dont want program crash due to invalid memory access.

Friends, could you please tell me if above logic would help me to avoid read-write lock.

Upvotes: 0

Views: 273

Answers (2)

Tudor
Tudor

Reputation: 62439

A read-write lock in a scenario with a single reader and a single writer is no different than a plain old mutex. Just use a mutex.

Upvotes: 1

NPE
NPE

Reputation: 500167

could you please tell me if above logic would help me to avoid read-write lock.

No, this logic will not let you avoid locking. The proposed scheme is full of race conditions.

My advice would be to use a single char array and a single mutex shared by the status and update threads. This will lead to very simple logic that will be easy to get right.

If -- and only if -- it turns out that this leads to unacceptable lock contention you should consider optimizing further.

Upvotes: 1

Related Questions