[MLton-user] Raw conversion of 32 bits into Real32.t

Matthew Fluet fluet at tti-c.org
Mon Jan 22 17:58:57 PST 2007


Wesley W. Terpstra wrote:
> On Jan 23, 2007, at 1:04 AM, Henry Cejtin wrote:
>> The  problem  of the thread-safe aspect of allocation outside a 
>> function call
>> has   already   been   solved.    Look    at    the    structure    
>> One    in
>> basis-library/util/one.sml.
>>
>> The signature is
>>
>>     sig
>>        type 'a t
>>
>>        val make: (unit -> 'a) -> 'a t
>>        val use: 'a t * ('a -> 'b) -> 'b
>>     end
>>
>> The  arg  to  make  is  the creation thunk.  A single copy is made and 
>> saved,
>> along with the thunk and a flag.
>>
>> When use is called, it checks if the single premade copy is in  use.   
>> If  it
>> isn't then it passes it to its second arg.  If it is then it makes a 
>> new one.
> 
> This is all well and good for the situation where there is a high cost 
> associated with the object creation. However, in Matthew's example, the 
> method was so small and its scope so narrowly defined, that I think 
> using 'One' is massively overkill.

I agree.  Especially in the multi-threaded case, the call to 
Thread.atomicBegin will be very expensive -- it essentially serves as a 
global lock.

Now, the ONE signature may suffice with a different implementation (say, 
with a compare-and-swap serving to guard access to the global object).

> I think my version (with the inline creation) should be preferable on 
> the grounds of simplicity and thread-safety. If things really need to be 
> optimized by the user, then your above solution is certainly appropriate.
> 
>> It is way better than having to re-allocate things every time.
> 
> Ok, I understand that the vector gets allocated on the heap. But the 
> naive programmer in me says: this should have been allocated on the 
> stack, ala alloca()!

It is difficult to allocate variable sized objects on the stack, since 
MLton needs to be able to walk the stack for garbage collection.

MLton will flatten away some tuples so that they are never allocated on 
the heap.  I could imagine doing something similar with arrays/vectors 
of statically known size; it would effectively turn the array/vector 
into a tuple, which would be flattened.

Unfortunately, in this particular example, where we are using the array 
to coerce between Word32.word and Real32.real, it wouldn't really work, 
since we're necessarily accessing multiple Word8.word elements at a time.





More information about the MLton-user mailing list