MC logo

Simple Two-Thread Test

^  Dr. Bennet

Tswitch

Main Page
F06 Assignment
Download Library
CCSC '07 Paper

Clients for Tswitch

Save And Restore
Restack
Multiple Stacks

Clients for the F06 Assignment

Simple
Thread Demolition Derby
Graph Search
This is a very simple test program which just creates and runs two threads. The output is:
First 4
Second 6
First 3
Second 5
First 2
Second 4
First 1
Second 3
First 0
Second 2
Second 1
Second 0
Returned 5 and 7.  Bye, now.

thlibt1.c Thread Demolition Derby>>
#include <stdio.h>
#include <string.h>
#include <thlib.h>

// This function is run by each of two threads.  They just loop and print,
// then exit with their first arg.
int fred(int i, char *msg)
{
        int origi = i;

        while(i--) {
                printf("%s %d\n", msg, i);
                th_yield();
        }
        th_exit(origi);
}

main()
{
        th_id_t t1, t2;
        int a, b;

        // Start the threads.
        th_init();
        if((t1 = th_fork()) == ARE_CHILD) fred(5,"First");
        if((t2 = th_fork()) == ARE_CHILD) fred(7,"Second");

        // Wait for them to finsh.
        a = th_wait(t1);
        b = th_wait(t2);

        // Say what happened.
        printf("Returned %d and %d.  Bye, now.\n", a, b);
}
Thread Demolition Derby>>