Jump to content

User:Eric B. and Rakim/Threads (computer science)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Eric B. and Rakim (talk | contribs) at 22:29, 14 October 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A thread is a line of execution for a program. Simple programs only have one line of execution and are therefore sometimes called single-threaded. This is an example of that kind of program in C:

       #include <stdio.h>
       
       int main()
       {
               int n;
               for (n = 0; n < 10; n++)
               {
                       printf("n is %d.\n", n);
               }
       }

Single-threaded programs are relatively easy to understand. They only do one thing at once and therefore only has one state at any time. The output of the program will be:

       n is 0.
       n is 1.
       ...
       n is 9.

When the computer executes the program, it executes all the instructions in the order they were typed. First it makes the variable n, sets it to 0, checks if it is less than 3, prints "n is 0.", adds 1 to n, checks if it is less than 3, prints "n is 1.", etc.

If a program has more than one thread it is called multi-threaded, and when it is executed it will do more than one thing simultaneously. Here is an example of a multi-threaded program written in C with pthread:

       #include <stdio.h>
       #include <pthread.h>
       #include <unistd.h>
       
       void print_even()
       {
               int n;
               for (n = 0; n < 5; n++)
               {
                       printf("n is %d.\n", n * 2);
                       sleep(1);
               }
       }
       
       void print_odd()
       {
               int n;
               for (n = 0; n < 5; n++)
               {
                       printf("n is %d.\n", n * 2 + 1);
                       sleep(1);
               }
       }
       
       int main()
       {
               pthread_t thread1, thread2;
               
               pthread_create(&thread1, NULL, (void *)print_even, NULL);
               pthread_create(&thread2, NULL, (void *)print_odd, NULL);
               
               pthread_join(thread1, NULL);
               pthread_join(thread2, NULL);
       }

To compile this program, you need to link with pthread. With gcc it is done like this:

       gcc -o program program.c -lpthread
Output of the two threads.
Output of the two threads.