C Study Guide

St. Gabriel's College

|

fork() and Multithreading

Many computers today have multiple CPU Cores. You may hear about a computer being "Dual Core" or "Quad Core", this is what they're talking about. A "Dual Core" computer has two cores, so it can do two things at the same time. This is called Multithreading, because we are doing multiple things at once.

Processes

To understand how this will work, you must understand how the computer knows how many programs are running. Each time you open a program, the computer creates a new process, which has a number called its process ID. The process ID is unique, no two processes can have the same ID.

fork()

To make a multithreaded program, we have to use the function fork which is in uninstd.h. fork() makes a "clone" of your program, creating a new process. Then both processes will run the rest of the code:

#include<stdio.h>
#include<unistd.h>

int main()
{
    fork();
    printf("This will be printed two times!\n");
    return 0;
}

However, there's still a problem, what if we want our two processes to do different things. We'll need a way to tell which process is the "real" process, and which one is the "clone" process.

I may get around to finishing this section later. However, the computers at school cannot use fork(), as it only works on Mac or Linux computers. If you have a non-Windows computer at home, here's an example program from the Wikipedia page about fork():

#include <stdio.h>   /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h>  /* _exit, fork */
#include <stdlib.h>  /* exit */
#include <errno.h>   /* errno */

int main(void)
{
    pid_t  pid;

    /* Output from both the child and the parent process
    * will be written to the standard output,
    * as they both run at the same time.
    */
    pid = fork();

    if (pid == -1)
    {
        /* Error:
        * When fork() returns -1, an error happened
        * (for example, number of processes reached the limit).
        */
        fprintf(stderr, "can't fork, error %d\n", errno);
        exit(EXIT_FAILURE);
    }
    else if (pid == 0)
    {
        /* Child process:
        * When fork() returns 0, we are in
        * the child process.
        */
        int  j;
        for (j = 0; j < 10; j++)
        {
            printf("child: %d\n", j);
            sleep(1);
        }
        _exit(0);  /* Note that we do not use exit() */
    }
    else
    {
        /* When fork() returns a positive number, we are in the parent process
        * (the fork return value is the PID of the newly created child process)
        * Again we count up to ten.
        */
        int  i;
        for (i = 0; i < 10; i++)
        {
            printf("parent: %d\n", i);
            sleep(1);
        }
        exit(0);
    }
    return 0;
}

Also this page talks about how non-Windows computers deal with fork().