Reputation: 29
I have the following struct
struct info {
unsigned long a;
unsigned long b;
};
atomic <info> data;
used by a writer thread and a reader thread. The reader has to respond to the new values as fast as possible. To do that I’ve implemented the following in the reader :
while (true) {
auto value = data.load();
// do some operations given these new values
}
This operation is very processor intensive. I’ve opted for this method because I believe it’s faster than, for example, using a condition variable and then waiting for the reader thread to be awakened when data changes. Also, the data updates quite frequently, hundreds of times per second. Is there a better way to do this while still having the fastest reaction time?
Upvotes: 2
Views: 1261
Reputation: 53317
A semaphore is indeed a good option to let a writer signal new data, while a reader wakes up whenever data is ready to be consumed. However, for high performance scenarios you should consider a lock-free queue, like the one written by Moody Camel. Such a queue allows writers to add new data entries without blocking the reader(s) and the reader can get data as fast as possible, without blocking the writer(s). That way data can be processed at maximum speed, if it is available and don't consume CPU resources otherwise.
Upvotes: 4