/*
Copyright (C) 2006-2008, The Perl Foundation.
$Id: /mirror/trunk/src/pmc/parrotrunningthread.pmc 35625 2009-01-15T16:56:07.509765Z jkeenan  $

=head1 NAME

src/pmc/parrotrunningthread.pmc -- Represents a running Parrot Thread.

=head1 DESCRIPTION

This type represents a running parrot thread.

It provides the following methods:
    - join
    - detach
    - kill

Note that a running thread object becomes invalid when a thread
finishes while detached or joined. Further operations on the
object may have unexpected behavior, such as manipulating an
unrelated thread.

=head2 Methods

=over 4

=cut

*/

#include "parrot/parrot.h"
#include "parrot/embed.h"

pmclass ParrotRunningThread no_ro {

/*

=item C<void init()>

Create a new, invalid handle to a running thread.

=cut

*/

    VTABLE void init() {
        PMC_int_val(SELF) = -1;
    }

/*

=item C<void init_pmc(PMC *tid)>

Create a new running thread referring to the thread with
the Thread ID specified in C<tid>.

=cut

*/

    VTABLE void init_pmc(PMC *tid) {
        PMC_int_val(SELF) = VTABLE_get_integer(INTERP, tid);
    }

/*

=item C<INTVAL get_integer()>

Return the thread ID of this thread.

=cut

*/

    VTABLE INTVAL get_integer() {
        return PMC_int_val(SELF);
    }

/*

=item C<void set_integer_native(INTVAL new_tid)>

Change the thread ID we refer to to C<new_tid>.

=cut

*/

    VTABLE void set_integer_native(INTVAL new_tid) {
        if (new_tid < 0)
            Parrot_ex_throw_from_c_args(INTERP, NULL, EXCEPTION_INTERP_ERROR,
                "Attempt to set invalid thread id %d", (int)new_tid);
        PMC_int_val(SELF) = new_tid;
    }
/*

=item C<METHOD join()>

Join the thread, returning whatever its main method returns.

=cut

*/
    METHOD join() {
        PMC *ret = pt_thread_join(INTERP,
            (UINTVAL)VTABLE_get_integer(INTERP, SELF));

        /* invalidate self */
        PMC_int_val(SELF) = -1;

        RETURN(PMC *ret);
    }

/*

=item C<METHOD detach()>

Detach the thread so it cannot be joined and will free its resources
immediately when it exits.

=cut

*/

    METHOD detach() {
        pt_thread_detach((UINTVAL)VTABLE_get_integer(INTERP, SELF));
    }

/*

=item C<METHOD kill()>

Terminate a running thread.

=cut

*/

    METHOD kill() {
        pt_thread_kill((UINTVAL)VTABLE_get_integer(INTERP, SELF));
    }

}

/*

=back

=cut

*/

/*
 * Local variables:
 *   c-file-style: "parrot"
 * End:
 * vim: expandtab shiftwidth=4:
 */
