bhavesh
bhavesh

Reputation: 1406

Avoid Frequent Locking

My program gets lots of data from exchange. The data is parsed into tick object. A typical tick

struct Tick
{
    string ID;
    int bidprice[5];
    int askprice[5];
    int totalTradedQuantity;
    int totalTradedVolume;
    .....
    .....
}

This tick object is published to network and logged in a file. Currently I am taking a lock for updating the tick and for publishing.

Parser Part:
lock();
tick update
unlock();

Publisher Part:
lock();
tick publish;
unlock();

As the frequency of data is high (5000 per second) I have to take a lock for each data received. Will it lead to performance issues? How do I avoid taking so many lock. Can anybody suggest a design implementation with minimum locking. Please help.

Upvotes: 1

Views: 239

Answers (3)

MSalters
MSalters

Reputation: 179779

Taking a lock is not bad. Lock contention is bad. How many locks do you have? One per tick, one per ID, one in total? Often the simplest solution is to avoid a single centralized lock.

Upvotes: 1

Max Lybbert
Max Lybbert

Reputation: 20031

Because you need mutual exclusion, you're going to need to lock. The best you can do with your current design would be to use unusual locks. For instance, if you read more than you write, you could use reader/writer locks. If there's little contention between threads and the same thread will often need the lock several times in a row, you might get a performance boost from biased locks.

However, I suspect that your better bet is a redesign. My favorite book on the matter is Is Parallel Programming Hard, and, If So, What Can You Do About It?. Every other parallel programming book I've read shows how to make threads communicate (e.g., through locks). This book shows how to design so that threads can run independently without a need to communicate (and, especially, without a need to coordinate through locks).

Upvotes: 1

sgun
sgun

Reputation: 899

Locking or semaphores are the only tools to prevent race conditions.

Semaphores will prevent busy wait. But locks(specifically spinlocks) will cause a busy wait. (In your case, data frequency is high; you shouldn't worry about busy wait.)

However, there are very efficient and fast locking mechanisms deployed to CPU. In this case you shouldn't worry about lock and unlock overhead.

Moreover, you always have the option to queue the requests and process them in a lock & unlock section.

Upvotes: 1

Related Questions