Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ThreadUnsafeDeallocator {
- public:
- concurrent_queue<void*> to_free;
- void* alloc(int);
- };
- Concurrency::concurrent_queue<std::unique_ptr<ThreadUnsafeAllocator>> allocs;
- struct ConcurrentDeallocator {
- ConcurrentDeallocator(ThreadSafeDeallocator* ptr)
- : from(ptr) {}
- ThreadUnsafeAllocator* from;
- void operator()(void* ptr) {
- from->to_free.push(ptr);
- }
- };
- std::unique_ptr<void, ConcurrentDeallocator> malloc(int) {
- std::unique_ptr<ThreadUnsafeAllocator> alloc;
- if(!allocs.try_pop(alloc)) {
- alloc = new ThreadUnsafeAllocator; // lock here
- } else {
- void* p;
- while(alloc->to_free.try_pop(p)) {
- alloc->free(p);
- }
- }
- auto p = alloc->alloc(size);
- allocs.push(std::move(alloc));
- return std::unique_ptr<void, ConurrentDeallocator>(p, ConcurrentDeallocator(alloc.get());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement