Multithreaded Programming Guide

A Simple Threads Example

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

The main thread wants the results of the lookup but has other work to do in the meantime. So it does those other things 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. This can be done here because the main thread waits for the spun-off thread to terminate. In general, though, it is better to malloc(3C) storage from the heap instead of passing an address to thread stack storage, which can disappear or be reassigned if the thread terminated.

Example 2-1 A Simple Threads Program

void mainline (...)
        struct phonebookentry *pbe;
        pthread_attr_t tattr;
        pthread_t helper;
        int 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];