Just An Application

June 13, 2013

Programming With Rust — Part Five: Things We Need To Know – Tasks And Memory

1.0 Tasks

The unit of concurrency in Rust is the Task.

Code executing in different Tasks runs concurrently.

To this extent a Task is analagous to a Thread in a language such as Java but with one very important difference.

Rust Tasks are memory independent as well as execution independent.

Code executing in separate Tasks cannot interact via shared memory.

This turns out to have a number of interesting ramifications.

2.0 Memory Access

Rust code executing in a Task has read/write access to three distinct areas of memory,

  • the current stack frame

  • a Managed heap belonging to the current Task

  • a global heap called the Owned heap

as well as read-only access to an area of static memory which is global and immutable.

2.1 The Current Stack Frame: Local Variables

Local variables can be allocated in the current stack frame like this

    let foo: uint = 5;

This creates an immutable local variable foo with the value 5;

A mutable local variable can be allocated like this

    let mut bar: uint = 5;

Local variables can hold simple discrete values such as integers as well as more complicated aggregates of values such as enum variants

    let white: Colour = RGB(255, 255, 255);

In this respect Rust is like C++ where fixed-size arrays or instances of structs or classes as well as integers, floats, etc. can be stored directly in a stack frame, and unlike Java where arrays and object instances can only ever be stored in the heap.

2.2 The Heaps

A Note On Terminology

I am not at all convinced that I fully understand the terminology used to describe the Rust memory model when it comes to heaps, so what follows is my own attempt at a consistent and hopefully accurate terminology.

A box is a piece of memory which has been allocated in a heap.

A pointer is a reference to a box which can be used to access its contents.

More specifically

  • a managed box is a box in a Managed heap

  • a managed pointer is a pointer to a managed box

  • an owned box is a box in the Owned heap

  • an owned pointer is a pointer to an owned box

2.2.1 The Managed Heap

Each Task has its own Managed heap which can only be accessed by code executing in that Task.

Each managed box may be referenced by multiple pointers.

If at some point there are no longer any pointers to a managed box it becomes eligible to be garbage collected.

The garbage collection of a managed box will occur at some time between the point at which it becomes eligible to be garbage collected and the point at which the Task which owns the Managed heap ends.

To allocate a uint in the managed heap of the current Task you can do this

    let cod: @uint = @5;

In this example both the local variable baz and the managed box are immutable.

You can allocate a mutable managed box like this

    let dab: @mut uint = @mut 5;

The local variable cod is immutable but the managed box is mutable.

You can obviously allocate things other than unsigned integers in a Managed heap. For example,

    let eel: @Colour = @RGB(0, 0, 0);

2.2.2 The Owned Heap

There is a single Owned heap which can be accessed by code executing in any Task.

An owned box can only be referenced by a single pointer.

An owned box is garbage collected at the point, if any, that it is no longer referenced by a pointer.

To allocate a uint in the Owned heap you can do this

    let bream: ~uint = ~5;

In this example both the local variable bream and the owned box are immutable.

You can allocate a mutable owned box like this

    let mut chub: ~uint = ~5;

And an example of allocating something other than an unsigned integer in the Owned heap.

    let dace: ~Colour = ~RGB(0, 0, 0);

2.3 Static Memory

A program’s static memory holds the values of items processed at compile time.

2.4 Enforcing The Semantics Of Managed And Owned Boxes And Pointers

The semantics of managed and owned boxes and pointers are enforced at compilation time.

2.4.1 Type Safety

Managed pointers and owned pointers are distinct types and they are not interchangeable, i.e. their types include where they are pointing as well as what they are pointing at.

For example you cannot do this

    let rudd: @uint = ~5;

nor this

    let scad: ~uint = @5;

2.4.2 Assignment Of Owned Pointers

Because there can only ever be one owned pointer to an owned box, if you do this

    let hake = ~17;

and at some point you then do this

    let goby = hake;

then from that point on the local variable hake is no longer usable.

2.4.3 Passing Owned Pointers As Arguments To Functions

If you pass an owned pointer to a function then ownership is transferred to that function.

For example, given this enum type

    enum FreshwaterFish
    {
        Loach,
        Perch,
        Roach,
        Tench,
    }

and this function definition

    fn catch(fish: ~FreshwaterFish)
    {
        ...
    }

if you do this

    let perch : ~FreshwaterFish = ~Perch;
    
    catch(perch);

then after the call to catch the local variable perch is no longer usable.

2.4.4 Returning Owned Pointers From Functions

If you return an owned pointer from a function then ownership is transferred to the caller of the function.

For example, given this enum type again

    enum FreshwaterFish
    {
        Loach,
        Perch,
        Roach,
        Tench,
    }

and this function definition

    fn catch_and_return(fish: ~FreshwaterFish) -> ~FreshwaterFish
    {
        fish
    }

then the net effect of this

    let tench: ~FreshwaterFish = ~Tench;

    ...
    
    let fish:  ~FreshwaterFish = catch_and_return(tench);

is to transfer ownership of the owned box from the local variable tench to the local variable fish.

3.0 Borrowed Pointers

You can borrow a pointer to a piece of memory irrespective of its location so long as the lifetime of the memory pointed to is guaranteed to be longer than the lifetime of the borrowed pointer.

This constraint is enforced by the compiler. If it cannot prove that the constraint is true then the code will not compile.

A borrowed pointer is declared using an ampersand (&).

For example,

    fn set_background(colour: &Colour)
    {
        ...
    }

The function set_background takes a borrowed pointer to a value of type Colour.

Because you can obtain a borrowed pointer to a value irrespective of its location the set_background function can be passed a Colour value that is stored in the current stack frame, or in the Managed heap of the current Task, or in the Owned heap, like so

    ...

   let s_white:  Colour = RGB(255, 255, 255);
   let m_white: @Colour = @RGB(255, 255, 255);
   let o_white: ~Colour = ~RGB(255, 255, 255);
   
   set_background(&s_white);
   set_background(m_white);
   set_background(o_white);
   
   ...

Note that to obtain a pointer to a local variable you use the & operator. The compiler will automatically create a borrowed pointer for a managed or owned box.


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

Advertisements

4 Comments »

  1. […] you might expect given the Rust runtime memory model there are three distinct types of […]

    Pingback by Programming With Rust — Part Six: Things We Need To Know – Lambda Expressions And Closures | Just An Application — June 13, 2013 @ 11:01 pm

  2. […] Rust string can be allocated in the managed heap of a […]

    Pingback by Programming With Rust — Part Seven: Things We Need To Know – Strings And String Literals | Just An Application — June 14, 2013 @ 8:07 am

  3. […] borrowed pointer to an IoTask, […]

    Pingback by Programming With Rust — Part Eight: Invoking The Listen Function | Just An Application — June 14, 2013 @ 9:41 am

  4. […] What we are defining here is a borrowed pointer. […]

    Pingback by Programming With Rust — Part Nine: Let’s Build A Program | Just An Application — June 14, 2013 @ 2:16 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: