Multithreaded Programming Guide

Simple Threads Example

In Example 2–1, one thread executes the procedure at the top, creating a helper thread that executes the procedure fetch(). The fetch() procedure executes a complicated database lookup and might take some time.

The main thread awaits the results of the lookup but has other work to do in the meantime. So, the main thread perform those other activities and then waits for its helper to complete its job by executing pthread_join().

An argument, pbe, to the new thread is passed as a stack parameter. The thread argument can be passed as a stack parameter because the main thread waits for the spun-off thread to terminate. However, the preferred method is to use malloc to allocate storage from the heap instead of passing an address to thread stack storage. If the argument is passed as an address to thread stack storage, this address might be invalid or be reassigned if the thread terminates.

Example 2–1 Simple Threads Program

void mainline (...)
        struct phonebookentry *pbe;
        pthread_attr_t tattr;
        pthread_t helper;
        void *status;

        pthread_create(&helper, NULL, fetch, &pbe);

            /* do something else for a while */

        pthread_join(helper, &status);
        /* it's now safe to use result */

void *fetch(struct phonebookentry *arg)
        struct phonebookentry *npbe;
        /* fetch value from a database */

        npbe = search (prog_name)
            if (npbe != NULL)
                *arg = *npbe;

struct phonebookentry {
        char name[64];
        char phonenumber[32];
        char flags[16];