Andrew
Andrew

Reputation: 1621

C++ - Fastest/reliable method of copying data to 2 different threads

Suppose I have 3 threads: A, B, and C. Thread B is a critical thread that needs to be as fast as possible while the other two threads are not as important. I am not using any mutexes for performance reasons as well.

I receive an update for an object in thread A. It is an object that is allocated on the heap. Thread A transfers this data to thread B via posting an event to an event queue for thread B. Thread B will update its copy of the object by clearing out the old memory and resetting the pointer to the new memory. Now there is a 3rd thread involved (thread C) that also needs this data whenever thread A receives the update.

If I try to transfer this data from thread B to thread C, then theoretically, thread B could be clearing out old memory at the same time that thread C is working with that chunk of memory (which will cause a race condition). It is OK if thread C is working with an old set of data. I just want to prevent the race condition. So in that case, should I have thread A create 2 copies of the data (one for thread B and one for thread C) and post an event to each of them? I don't want to create a copy while in thread B because that thread needs to be as fast as possible.

Upvotes: 1

Views: 471

Answers (2)

Shachar Shemesh
Shachar Shemesh

Reputation: 8563

I'm not 100% sure what the question is. If it is about memory management (i.e.- when to free the memory), just use a shared_ptr (either the C++11 or boost). Then the last thread to get rid of the pointer will release the memory.

Also, you claim you don't have any mutexes, but you are using an event queue. That event queue has a mutex in it. If it works fast enough for you, in all likelihood, a mutex at the right place will too.

Upvotes: 1

qqibrow
qqibrow

Reputation: 3022

I don't know whether I fully understand the question, correct me if I am wrong.

So the problem here is that thread B and thread C may working on the same chunk of data and you don't want use lock considering the performance.

So why not add a DataPool layer between thread B and thread C? This DataPool will preallocate enough memory and your thread B will ask it for new memory. Once it's done, thread B pass the pointer to a blocking queue and thread C will start working on that. Once thread C's done, it will call the DataPool to recycle.

It is possible that thread B may wait for thread C because DataPool doesn't have any free memory and everyone is waiting for thread C to call DataPool to release memory. Firstly, you could enlarge the dataPool and test what's the best size to avoid the problem. Secondly, if thread C is not so important, DataPool could force thread C to terminate and get some free memory.

Upvotes: 0

Related Questions