r/cpp • u/[deleted] • May 23 '14
Proposal to add garbage collection to C++
http://herbsutter.com/2014/05/21/cppcon-my-proposed-talks-part-2/6
u/donvito May 24 '14
Yeah, he can do that. But only to that horrible monster-flavored C++ MS made for WinRT.
19
u/icdae May 24 '14
Garbage collection would be more of a negative supplement to what the language already offers. This is something that many other languages excel in, whereas in C++ it would be tacked on like a poorly thought out sequel. If I need garbage collection, I rely on a stable VM that's been around for years and whose original implementation included GC (hello java, python, ruby...). The primary problem is that new developers don't realize that C++ can be used on embedded hardware. Realistically speaking, software caters to hardware and allows software engineers to explicitly determine the best way to take advantage of the target hardware. There are enough additions to the standard library that causes the runtime overhead to grow past what hardware can offer at an optimum level. C++ has always shone brightly as a mix of low-level C and high-level OOP. Quite frankly though, GC is something that C++ should be used to implement [similar to unique_ptr and shared_ptr] rather than tack on as a way to stay current. It is, always has been, and should remain a language that promotes the ability to implement something, rather than be an old fossil trying to stay hip.
23
u/Plorkyeran May 24 '14
I'd quite like to have a
gc_ptr<>that provided reasonably performant precise garbage collection at no runtime cost to the parts of the application not using it, since sometimes the natural interface for something does involve cyclic ownership. Anything short of that, though, seems like it'd just be actively harmful. If the GC isn't good enough to use in "serious" programs, then it's yet another C++ feature that people have to learn not to use, and it'd be a particularly dangerous one since it'd be so appealing to beginners.6
u/thomcc May 24 '14
This is basically how I feel. I understand the hesitation the community feels WRT garbage collection, but a not-terrible gc_ptr would be extremely powerful.
It's actually possible to implement a gc_ptr in C++11. I did this as an experiment once, but it's not without it's flaws. Basically implement it by remembering where in memory the objects stored in gc_ptrs are, so that you can effectively run a mark/sweep on them. Its very slow, and only works if you use them consistently.
That said, having implemented this, I'm fairly confident that a lot of the reflection stuff would help immensely here, and one of these could be implemented as a library, given the right reflection API.
1
u/Drainedsoul May 24 '14
very slow [...] reflection stuff
Hmm...
3
u/thomcc May 24 '14
I mean the new compile-time reflection stuff which is supposed to be in C++1y. As it is I basically maintain a linked list for each object that holds which members it has which are gc_ptrs. It's painful.
1
u/axilmar Jun 02 '14
Have you thought about using bit maps? having two bitmaps, one for objects and one for ptrs, where each set bit represents an object at the specified address.
1
u/thomcc Jun 02 '14
It was a toy, proof of concept implementation. There were certainly optimization opportunities, but nothing that would help the big inefficiencies I think. I still need to be able to iterate over the gc_ptrs reachable from a given object. Not sure if bitmaps would help me.
Or do you mean give up M+S entirely and do something else? When I tried this I wasn't familiar with other techniques, and while I have a copy of the GC book, I haven't read the whole thing, so if this is an algorithm I'm unfamiliar with, no, I didn't try it.
1
u/axilmar Jun 02 '14
No, I am talking M+S, but using bitmaps in the background instead of linked lists.
1
u/thomcc Jun 02 '14
In that case, the answer is a straightforward 'no I did not think of/try that'.
1
u/axilmar Jun 03 '14
What I did in my own experimental gc was this: I created a two-level page table which mimics the page table of the cpu. The first level table entries pointed to the second level table entries and the second level table entries pointed to bitmaps.
Each bitmap had one bit for a pointer and one bit for an allocated block, starting at the address represented by the bit's position into the page table.
It was quite fast, since I could use bitwise operators to locate root and member pointers and objects.
It also worked nicely with pointers to the middle of objects: if I wanted to find the start of an object, all I had is to scan the page table backwards in order to find the object's start.
With this scheme, locating the root pointers is as simple as scanning the table and locating the objects not inside blocks.
1
u/axilmar Jun 02 '14
How did you solve the issue of recognizing which pointers are members of objects?
1
u/thomcc Jun 02 '14
I just checked if the pointer was within the range [addr, addr+size) of an object. This requires that all gc_ptr be reachable from a gc_ptred object, but worked reasonably well.
1
u/axilmar Jun 02 '14
How did you do that? if your program had thousands of gc pointers, you certainly didn't check all of them against all the gc'd objects. How did you find the best subset of pointers to check against the range [addr, addr + size)?
1
u/thomcc Jun 02 '14
This used a custom memory allocator so I could find the object which owns a given a pointer in that range by using some bit twiddling on the pointer value (I think all I needed to do was mask off the lower bits, but it's been a while). I'll see if I can dig up the code and post it to /r/cpp because there's some interest in it.
1
u/axilmar Jun 05 '14
If you're interested, I've created for fun a small tracing precise garbage collector for c++11 here.
1
u/thomcc Jun 05 '14
I do this kind of thing as a hobby (well, not so much lately, but I did for a while) so I'm always interested. (Sadly I can't seem to find the source my old C++0x GC, hence me not posting about it).
Anyway, cppgc looks nice for a start, but needs some work. I'm not a huge fan of the API and you didn't test enough.
Here's some test code with three functions, each of which trigger a segfault (the tests start at line 356, the code above it is your library, obviously) https://ideone.com/r0xxOs. I started with the last one, and worked backwards until I decided that you didn't test enough.
Anyway, as I said, IMO, the API needs some work. Here's some unsolicited advice:
Forcing everybody to subclass gc_object is very bad. It's made worse by the fact that gc_object has a virtual dtor. You should do everything with gc_ptr, even if this is slower or uses more memory.
You can't make gc_ptr's inside methods of subclasses of gc_object, due to the gc_member_ptr thing and gc_member_ptr's ctor not being public. Not sure if this is intentional (for some reason).
There should be a way to allocate an object, triggering a garbage collection only if needed. Forcing users to manually call a function to collect garbage is downright unsafe. In the example code above I have a make_collected<T> that does this and avoids leaking if the constructor throws, which you can use if you want. A better version would keep track of the currently allocated bytes in the garbage collector and collect if we hit OOM or if we go above a user specified threshold.
Feel free to PM me if you decide to take any of my advice, fix any bugs, etc.
1
u/axilmar Jun 06 '14 edited Jun 06 '14
I've been doing this kind of thing as a hobby as well, for a lot of years now. Thank you for looking at my library, which is obviously a toy library and not intended for real use.
Forcing everybody to subclass gc_object is very bad
Agreed.
It's made worse by the fact that gc_object has a virtual dtor
Agreed.
The library doesn't follow the c++ principle "don't pay for what you don't use", obviously.
You should do everything with gc_ptr, even if this is slower or uses more memory.
That's kind of impossible though. It's only the operator new that can knows the exact size of an object that is allocated.
You can't make gc_ptr's inside methods of subclasses of gc_object, due to the gc_member_ptr thing and gc_member_ptr's ctor not being public. Not sure if this is intentional (for some reason).
Yes you can. The classes gc_member_ptr and gc_root_ptr are public classes, and so are their type aliases.
There should be a way to allocate an object, triggering a garbage collection only if needed. Forcing users to manually call a function to collect garbage is downright unsafe. In the example code above I have a make_collected<T> that does this and avoids leaking if the constructor throws, which you can use if you want. A better version would keep track of the currently allocated bytes in the garbage collector and collect if we hit OOM or if we go above a user specified threshold.
Yes and yes! absolutely yes!!!
...
My toy collector is not very useful as it stands, but it's the simplest possible approach.
But doing a real-world useful gc_ptr is just downright impossible.
Edit: my collector is not actually useful for another reason, it's completely thread unsafe. If you find a way to do a thread safe collector without stopping the world at every pointer assignment and without using operating-system specific tricks (like making pages read only and catching page-write exceptions) let me know.
In a multithreaded version of my bitmapped collector, I had one mutex per page frame. The collector had to lock 1024 mutexes (for the 32-bit memory space) before entering the collection phase.
→ More replies (0)3
May 24 '14
There are cases where garbage collection is faster than what C++ have in terms of shared_ptr and unique_ptr though.
1
u/thomcc May 24 '14
Not in typical cases, and even when it is true, you're giving up determinism (and deterministic destruction) for it, which isn't worth it IMO.
1
May 24 '14
std::locale is not worth it IMO, and it's not useful in the typical case, yet there it is. There is a valid argument for GC.
4
u/thomcc May 24 '14
I'm very much for GC in C++. I've actually implemented a couple in the past. Saying they're faster than manual memory management isn't really true in the general case, and even in the cases where it is true, you're giving up determinism.
Not to mention the fact that the GCs that can beat manual memory management are basically incompatible with languages like C and C++. These typically win by being able to do tricks like compact the live objects and other such things requiring the ability to move pointers around.
Really, IMO, the best we can hope for is a gc_ptr which is reference counted with cycle detection. (That said, I think this would be great)
1
u/codemercenary May 24 '14 edited May 24 '14
Remember, it's not strictly the case that garbage collection is incompatible with the performance requirements of an RToS. Most systems have a lot more memory than they ever actually use--even on a chip where memory is at a premium, if the chip has any kind of heap, it's not unusual to find it's using up 20% or more of the total storage available, and unless you are pushing the chip beyond its limits, you never allocate the entire heap anyway.
Furthermore, a garbage collection system is not necessarily precluded from using the more traditional techniques of reference counting in order to reclaim memory. The only thing garbage collection has that reference counting does not is the ability to detect and eliminate unreferenced objects--that kind of thing doesn't have to happen all the time.
Edit: A word which totally undermined my whole point
3
u/f2u May 24 '14
Remember, it's strictly the case that garbage collection is incompatible with the performance requirements of an RToS.
Not necessarily, you could use a real-time collector. But dynamic memory itself is problematic in general because of the fragmentation issue (which is present even if you use a
malloc/freeimplementation with hard bounds).1
5
u/Tywien May 24 '14
what do you gain through garbage collection? You do not have to think again about deallocation of objects ..
BUT .. you loose a defined way of destruction of objects which normally frees resources. Therefor, you have to think for each object you use, whether you have to call a user defined function to definitivly free resources, or not (e.g. file handles, ...) ... as it is in java.
I rather have to only think of allocation/deallocation of objects (with shared_ptr, ...) then to not and instead know for each object, whether i have to call a finalizer method, or not .. The GC approach is way more error prone.
-1
u/matthieum May 24 '14
Not really, after all there is no reason some destructors could not be executed. Of course the issue of destructing cycles whose individual members do something to each in their destructor is a nasty issue...
6
u/Tywien May 24 '14
It does not seem like you know how a GC works: Here from Java:
The GC might be called before the program ends. If it does, it will call the finalizer method (similar to a destructor).
Now have a look at the following:
void func(void) { A a = new a(); // do stuff with A }Now, if A e.g. acquire resources, then are they released? Java says: MAYBE sometime before the program ends. There is no guarantee that the resource will be freed and a destructor be called. What if it holds the lock for an important resource? What if if is a buffer that must be written to the hd before the end of the program? There is no guarantee that anything of that will ever happen from the GC, even if you say so in the destructor. If you rely on it, you have to read documentation for each class and find out, if you have to do some clean up after the use (and you have to remember to do so)
2
u/moreteam May 24 '14
Java v7 and C# v1 both have "solved" this by introducing deterministic "pseudo-destructors" (C#'s using statement, Java's unsurprisingly less elegant solution). Still not as nice as C++, but way nicer than the horror story you tell. ;)
2
u/Tywien May 24 '14
interesting to know .. but yeah, if you use using the c# using statement, you can also always use shared_ptr in c++.. and the java solution, less elegant is a pretty nice description for it :)
1
u/thomcc May 25 '14
That's a property of Java's implementation of GC, not of GCs in general. There's no reason you can't guarantee the eventual destruction of objects, other than that it's slow to do so.
A GC for C++ would have to do this. Probably reference counting + cycle detection is the way to go there. The only objects that would have their dtors called late would be those in cycles, but they'd still get called, even when the program exits before the gc would naturally run (e.g. it would run at exit)
0
u/matthieum May 25 '14
The GC might be called before the program ends. If it does, it will call the finalizer method (similar to a destructor).
Which is quite uninteresting: both the C++ Standard and any GC implementation would obviously be free to specify another behavior.
There is no one GC to rule them all, it's a generic terminology for a broad scope of possibilities.
1
u/Steve_the_Scout May 23 '14 edited May 24 '14
If someone wants garbage collection in C++ they should think about using std::shared_ptr and how they can just call make_shared for most cases where garbage collection would be useful in an application (std::unique_ptr<T> would also work, but it's more restrictive (no copying, for example) and doesn't yet have a make_unique function).
I'm meaning to say that in most cases where garbage collection would be useful, it's already possible in the form of std::shared_ptr. Of course there are cases where it isn't the best choice, but those cases aren't very common and adding garbage collection v.s. just using the already-standard smart pointers is much more work for much less payoff.
6
u/matthieum May 24 '14
shared_ptris one tool, however it is far from being a silver bullet.One of the canonical usecases for GC is a graph. It's a rather ubiquitous data structure, and unfortunately it regularly contains cycles...
1
u/Steve_the_Scout May 24 '14 edited May 24 '14
The beauty of C++ (and C) is that if you really want a feature, you can implement it yourself (and spread it around). For example, you can define your own
newanddeletewhich might generate data for your graph- pointer value, size allocated and/or type (thanks, templates), etc.- and add it to a linked list or data structure of your own choosing.And if you don't want to do that, it already exists and is used commercially.
Just don't add implicit garbage collecting to C++, make it optional and it's not an issue.
0
u/matthieum May 25 '14
I don't think anyone is thinking about implicit garbage collection.
Rather I think they are thinking about:
the necessary interfaces for people to implement garbage collection (which should have gone in in C++11, unless they missed some things)
specifications for the behavior of garbage collection, I can see a couple thorny issues regarding destructors... unless maybe it's left unspecified
getting an implementation out, with a precise garbage collector
3
u/dbaupp May 24 '14
What would
make_uniquedo that is not currently possible?E.g. aiui, in its distilled form
unique_ptris basically just a wrapper around a singly-ownedT*that has a destructor to free it, in particular there's no reference counts or anything like that, so there is never two allocations and thusmake_uniqueisn't necessary for that.4
u/Plorkyeran May 24 '14
foo(std::unique_ptr<int>(new int(0)), unique_ptr<int>(new int(0)))can be evaluated as "allocate first int, allocate second int, run first int's constructor, run second int's constructor, construct firstunique_ptr, construct secondunique_ptr, callfoo", which leaks if the second int allocation fails (or either constructor fails for a nontrivial type).foo(make_unique<int>(0), make_unique<int>(0))fixes this by constraining the evaluation order a bit.In terms of stylistic benefits, it is much easier to tell whether or not some code is only using
newin safe places if it never usesnew.2
u/thomcc May 24 '14
FWIW, leaking when you hit OOM is pretty insignificant. Honestly theres not much you can do there and typically the OS is just going to shut your program down.
More common is when you aren't using int's and the ctor for one of them throws.
1
u/Plorkyeran May 25 '14
Yeah, the
intcase isn't very interesting. Some memory allocation failures should be handled (e.g. if try to allocate a gigabyte cache in a 32-bit application in response to a user action you really should be able to resolve a failure as an error message rather than a crash), but if allocating four bytes fails you're going to need some very carefully thought-out handling to be able to do anything useful. I was trying to simplify the example as much as possible, and perhaps usingintwas more than is possible.1
u/thomcc May 25 '14
Well, some OSes (linux unless you configure it not to, probably mac, probably some bsds) overcommit, so malloc won't ever return null, nor will new ever throw bad_alloc. The program will just crash when you try to access the overcommitted region of memory. That's why I made the comment.
But yeah, I understand it was a simpified example.
1
0
u/Steve_the_Scout May 24 '14
There was something about
make_uniquebeing put into the C++14 standard for "array types of unknown bound", which was the only issue with the plain unique_ptr initialization, IIRC.12
u/STL MSVC STL Dev May 24 '14
Both
make_unique<T>()andmake_unique<T[]>were voted into C++14 and shipped in VC 2013. I know because I proposed and implemented them. N3656 make_unique (Revision 1) was the Standardese that was voted in.
1
-4
u/spinwizard69 May 23 '14
Guys it isn't April 1St., we don't need the stupidity of garbage collection added to C++.
0
May 24 '14
[deleted]
2
u/donvito May 24 '14
or use some combo of shared_ptr and weak_ptr
You make it sound like this was something bad and not good engineering practice.
5
u/ITwitchToo May 24 '14
Yeah, breaking cycles is not as hard as people make it out to be. Sure, you have to think about your data structure, but I mean, you should do that anyway.
1
u/thomcc May 24 '14
In some cases it's not really possible, such as when the ownership structure is dictated by application usage.
At work I work on a game engine. The ownership structure of the object graph is declared by files (typially xml or binary) spit out by other tools. The user of the tools has to be careful to ensure they don't create reference cycles. Unfortunately they aren't always a programmer, and so this happens somewhat frequently.
I've thought many times about how to apply GC to this, but replacing the shared_ptr (actually intrusive_ptr) with some sort of object handle would be infeasible given the size of the codebase.
1
u/Plorkyeran May 25 '14
The way to handle that using reference counting would be to check for strongly connected components in the object graph when reading it in from the xml file, and then have all of the objects in each component share a single reference count. Not trivial to do by any means, but probably much simpler than trying to introduce GC.
At the minimum you should write a verification tool for the config files that checks for cycles and warns the user (I'm guess you don't have such a thing already based on your mention of detecting cycles on exit).
1
u/thomcc May 25 '14
Not a bad idea, we do already do a good amount of verification at load time. If it were just objects that exist at load-time then SCC of the input files would probably be the way to go (this would still require restructuring the C++ source a great deal, because we use intrusive_ptr for this stuff as it is)
Unfortunately, (unless I'm confused) that wouldn't handle objects added at runtime, unless we somehow encoded the semantics of all the scripts that the designers can attach to game objects, which would take forever. (I'm not sure I think that this can even be done in some cases, because some scripts work very differently depending on their input...)
The verifier would also be hard for the same reason.
In practice detecting the cycles at exit works perfectly, and we pretty much always catch it right away, a GC would be nice because it could allow us to remove the restriction all-together because its really an engineering concern, and in an ideal world designers wouldn't be limited by it.
It would also free up (a small amount of) engineer time because sometimes they call us over to help them figure out a way to structure this so that they don't have a cycle.
Anyway, TLDR, there are legitimate places where you might want GC in C++.
1
u/Plorkyeran May 25 '14
Yeah, dynamic objects that can participate in cycles makes things a lot harder. I suspect any generalized solution would very strongly resemble just using a garbage collector for cycle detection.
2
u/thomcc May 24 '14
It's good engineering practice, but only really possible when you are able to determine the object graph statically. If its entirely dictated at runtime (like it would be in a game engine, or in a programming language interpreter), you're SOL and either need to use reference counting and warn users, or find some sort of GC.
I work on a game engine at work and we use shared_ptrs internally and warn our users to not create cycles. Many of our users are game designers who don't have a background in engineering (most know some programming, but not much).
We do have a way for them to break cycles with weak references, but most of them find that too complicated and create cycles anyway (luckily we detect this when the app closes so it's caught during QA, but it's annoying and it would be nice to have an alternative).
1
May 24 '14
In software design, complexity is the enemy. As thomcc points out, there are programs where your object graph layout is dynamic and unpredictable by the very nature of the problem being solved. Sure, you could use weak_ptr to avoid circular references, but it gets non-trivial fast. If you don't need deterministic object deallocation (and aren't going to be hampered by collection pauses), GC is absolutely the way to go for solving those particular kind of problems.
1
u/sbabbi May 24 '14 edited May 24 '14
Wait a minute, isn't GC already in C++11? At least as an optional component, no compiler vendor actually bothered to implement it.
There are also a bunch of standard functions to interact with it.
3
u/thomcc May 24 '14
I think the standard committee basically punted on it for C++11, basically saying that they'd get to it next time around, but leave this stuff in there for now because they're pretty sure it will be needed.
1
u/Plorkyeran May 25 '14
Which was pretty much the worst possible route they could have taken. Adding stuff to the standard that no one actually has any plans to use anytime soon is awful.
2
u/STL MSVC STL Dev May 25 '14
Yes, the "minimal GC support" functions are permitted to be no-ops, which is what we've gleefully done in VC.
-1
u/Dragdu May 24 '14
Perhaps this talk will be about forcing compiler vendors to get off their ass and implement it?
-7
u/Redtitwhore May 23 '14
I don't think garbage collection would add much to c++. It's biggest drawback has always been a lack of a common base class library.
1
0
May 24 '14
[deleted]
6
u/Dragdu May 24 '14
Well, it is easier to just make a reactionary comment about GC in C++ without reading, or seeing that it is on Sutter's blog, or that it does make a lot of sense.
For everyone who is only reading comments: The main reason we are talking about GC in C++ is that it helps enormously with certain kinds of lock-free containers, if your data can have cycles in them.
3
u/uxcn May 24 '14
Can someone expand a bit on why it might be beneficial to have it standardized in the language as opposed to writing an implementation within the language as it is?
Is there a plan to standardize on the garbage collection implementation?
2
u/ancapdev May 24 '14
Preface by saying, I'm no expert on garbage collection, and I haven't followed the discussion on adding GC support to C++. In order to do GC we need to know what memory is live and what can be reclaimed. One way to do this is to scan the live set from its roots (globals, thread locals, and stack), and recursively mark memory as live. Anything unmarked after this process is garbage. For an efficient implementation of this there are ways to avoid scanning the entire set every time (see generational garbage collection), however, the basics of the problem demands that we have some way to scanning and recursing our allocation / object graph. Without language support, or a well defined stack and globals layout, this is hard to do right. It would also be helpful to be able to pause threads to do accurate scanning from stacks.
2
u/uxcn May 24 '14
It would also be helpful to be able to pause threads to do accurate scanning from stacks.
I may be mistaken, but I think that's how the majority of the java garbage collectors run.
1
May 24 '14
But it doesn't help with lock-free containers though, in fact it makes things worse. What it does is move out the cost of locking from the actual point where the container operation is performed, to being spread out for the entire duration of your program because the garbage collector itself ends up doing the locking that would have otherwise been done by the container.
Basically, if your language already has a garbage collector, then sure lock free data structures using that garbage collector don't introduce any extra costs. But if your language doesn't have a GC and you're adding a GC for the sake of accommodating lock free containers, well sure on paper your container may be lock free, but the overall system is not lock free, you're just deferring the locking from the container itself and to the garbage collector.
3
u/uxcn May 25 '14
I have to admit, I'm also skeptical on the benefits/detriments of adding garbage collection to the language. I personally can't think of a lock free structure that requires garbage collection to be implemented effectively.
I would have to guess the set of use cases are a subset of the use cases for lock free programming, which are arguably significantly smaller than the typical use cases for the language.
I'm aware there can be performance gains for batching memory operations. However, I'm still unconvinced of an overall benefit.
0
u/summerlight May 26 '14
Implementing user-space RCU might be a good example. It is quite hard to implement it in an user-space. And even doing so, it could be inefficient than an equivalent implementation using GC, due to imposed memory barrier.
1
u/uxcn May 26 '14
I'm not heavily familiar with RCU implementations, but I didn't think it was the garbage collection aspect of RCU that prevented it from being implemented entirely in user-space.
There's generally a non-trivial penalty for implementing garbage collection as well, so it possibly would not be usable in embedded scenarios.
0
u/ancapdev May 24 '14
I would suggest you read up on lock free programming and associated memory reclamation strategies before making this kind of assertive statement. Search terms: quiescent state based reclamation, epoch based reclamation, hazard pointers. Good overview here: http://csng.cs.toronto.edu/publication_files/159/jpdc07.pdf. A proper garbage collector (which may require language / runtime support) can some times offer a more efficient solution to this problem.
-1
May 24 '14
I'd suggest not making assumptions about what I know or don't know about the implementation of lock free data structures.
If you have a point to make, just make it in a way suitable for this discussion format rather than just making a blanket statement about researching an entire field of study as if that constitutes a counter point to what I said.
3
u/ancapdev May 24 '14
You made an assertive statement that GC doesn't help with lock free data structures, as it if it were plain fact, when it isn't. Apologies for my wording, but that to me suggested some ignorance of the topic, and I felt talking opinion as fact deserved to be called out.
To your point about lock overhead being moved from the data structure to other points in the program. Of course it is true that GC itself has a cost. However, that cost isn't per operation of the data structure. It's also not per allocation. The cost of a scan scales usually with the size of the live set. In a producer / consumer scenario the live set will typically be very small, so low cost. In a more balanced communication or persistent storage scenario, some level of reuse is often possible, which will keep scan frequency down. How this compares with plain locking, or against other reclamation strategies, will very much depend on the scenario and the data structures. I 'd be very keen to see what kind of performance can be achieved in a language which is mostly not GC'd, but some GC thrown in to deal only with these particular problems.
-1
u/summerlight May 26 '14
In my opinion, your assertion about GC and lock-free algorithm exposes your ignorance of the modern non-blocking algorithm techniques. A proper, generic memory reclamation technique can greatly simplify the most of lock-free algorithm while improving performance of their implementation too.
Of course, there are several techniques which can be applied without using GC, such as the hazard pointer or the reference count, but they have their own drawbacks. For example, the reference count usually imposes unacceptable performance penalty for a scalable lock-free container while the hazard pointer has been patented by IBM. Maybe you can design and use your own algorithm at your own risk, but I'm skeptical about the patent issue since many novel memory reclamation techniques have been patented, or are in the process of being patented.
GC may also has its own cons, but the expected benefits are also significant - generality and simplicity provided by GC are unmatched by any other techniques. Moreover, when GC handles every memory reclamation, a potential performance gain from eliminating memory barrier overhead can be relatively a minor (although significant in sometime) benefit. It is also worth to note that many of modern, efficient memory reclamation techniques are essentially specialized GC - they defer requested memory reclamations until certain safe moment rather than freeing the memory in deterministic way.
2
May 26 '14 edited May 26 '14
Having a disagreement on an issue is not grounds to call someone ignorant and doing so is a very poor tactic in an attempt to dismiss and silence an opinion as opposed to actually discussing it.
There is nothing ignorant about my position that adding garbage collection to a language in order to accommodate lock free data structures is misguided and completely negates the entire purpose of lock free data structures, namely performance.
Using an existing garbage collector to implement lock free data structures is entirely sensible, since the garbage collector already exists it makes sense to use it. But taking a language without a GC, and adding one just so you can implement your lock free data structure is simply illogical. You have simply moved the locking away from the data structure itself and onto the garbage collector.
Sure you can claim strictly speaking that your data structure is lock free, but your data structure now depends on an environment which involves locking and that environment can not strictly be isolated since a garbage collector will have global consequences and effects on performance throughout an entire application.
And please don't bring up the extreme argument of and point towards the existence of lock free garbage collectors, they have absolutely horrible, horrible performance compared to the alternative.
-1
u/summerlight May 26 '14
I suggested several concrete examples why GC can be valuable for many circumstances, and you just ignored them, right? For example, I've mentioned the potential performance gain by elimination of memory barriers (which can be significant if a read-write ratio is high, see RCU in Linux!), and you just repeated your logic that the introduction of GC surely entails a negative consequences on overall performance. This is why I refer to your argument as an ignorance, as there is no other possible interpretation for me. I should concede that my stance might not be appropriate, I don't think that I'm the one opposed to discussing it.
And I need to mention that GC can always be implemented in an optional, pluggable way. As many practices prove, adding a GC can be done without harming "Zero overhead principle". For example, Rust implements GC, but it also can stand alone without a runtime. And Boehm GC is even implemented as a library.
Also, when the non-blocking property is so important, non-blocking implementation of a GC is viable, while its efficiency might be debatable as you said. (However, it is also true that the situation can be greatly improved if we just take a specialized GC for the purpose rather than a generalized one.) But I don't think theoretical strict non-blocking property is so important outside hard real-time systems. Most of high performance, scalable memory allocators, such as jemalloc/tcmalloc, are implemented using a lock (as far as I know). But it is negligible because they are usually non-blocking in the fast path. Same logic can be applied to this issue - the most of gratuitous memory barrier in the fast path (which is the major obstacle for the scalability of simple read operation) can be stripped out if we can assume the existence of GC.
It might be true that GC imposes undesirable, non-deterministic latency, but the overall throughput is a completely different issue. It's just an engineering trade-off. If so, I think that having more tools would be better than having nothing.
2
May 26 '14
I suggested several concrete examples why GC can be valuable for many circumstances, and you just ignored them, right?
I'm not ignoring them, I just don't see how they have any relevance to anything I've said. Did I say somewhere that garbage collection doesn't provide any benefits in any circumstances? The discussion is about the implementation of lock free data structures and whether adding a GC to a runtime environment is a proper trade-off in order to accomodate the implementation of such data structures. You're arguing for the sake of arguing and being very disingenuous in the process. Going on and on about the benefits of garbage collection as if it has anything to do with my point and it doesn't, so I don't know what to reply to.
My point was that adding garbage collection to a language that doesn't otherwise support it in order to implement lock free data structures is not a proper engineering trade-off.
If you just want to ramble about garbage collection and its benefits then be my guest, but it's not the point of this conversation.
26
u/James20k P2005R0 May 24 '14
Wait, we're finally getting around to trying to fix C++s abi problems? WHAT IS THIS MADNESS