GC, the simple solution

Walter Bright newshound at digitalmars.com
Fri Jun 9 01:35:17 PDT 2006


Sean Kelly wrote:
> Derek Parnell wrote:
>> On Thu, 08 Jun 2006 22:18:24 -0700, Walter Bright wrote:
>>
>>
>>> The approach most real time programmers use to deal with this is to 
>>> preallocate all needed data before entering the real time section, 
>>> and the real time section does no malloc's or free's.
>>>
>>> Also, you can use malloc and free in D, in exactly the same way you 
>>> would in C.
>>
>> It seems obvious that if one doesn't want the Garbage Collector to 
>> collect
>> garbage, one doesn't create any garbage for it to collect. ;-)
> 
> This gets sticky if one wants to use strings in D though, as there's no 
> real way to make them work outside of the garbage collector mechanism.
> Sure we could use C-style pointers, but it's not a terribly attractive 
> option.

You can use D arrays. Just allocate them using malloc (or statically 
allocate them). Don't concatenate them.

Though I would ask why the real time code was allocating strings?

C is very good for writing real time code, and you can write "C"-style 
code in D, and it will behave exactly like the corresponding C code. You 
can call printf, strcpy, malloc, etc., which will behave just like C's 
printf, strcpy, and malloc because they *are* C's functions. It will not 
do a gc collect unless the code allocates gc memory, and it will ONLY do 
a gc collect during such an allocation.

Heck, my old Empire game was written in C. I renamed the files from .c 
to .d, did a few minor syntactic edits, and voila! it was now in D. It 
runs exactly the same.

But the bottom line is that a real time thread should not be doing 
storage allocation. It shouldn't be calling new, or malloc. It shouldn't 
do storage allocation regardless of whether it is written in D, C, C++, 
or assembler.



More information about the Digitalmars-d mailing list