4. threads.c example

$ cat -n ostep/code/intro/threads.c
     1	#include <stdio.h>
     2	#include <stdlib.h>
     3	#include "common.h"
     4	#include "common_threads.h"
     5
     6	volatile int counter = 0;
     7	int loops;
     8
     9	void *worker(void *arg) {
    10	    int i;
    11	    for (i = 0; i < loops; i++) {
    12		counter++;
    13	    }
    14	    return NULL;
    15	}
    16
    17	int main(int argc, char *argv[]) {
    18	    if (argc != 2) {
    19		fprintf(stderr, "usage: threads <loops>\n");
    20		exit(1);
    21	    }
    22	    loops = atoi(argv[1]);
    23	    pthread_t p1, p2;
    24	    printf("Initial value : %d\n", counter);
    25	    Pthread_create(&p1, NULL, worker, NULL);
    26	    Pthread_create(&p2, NULL, worker, NULL);
    27	    Pthread_join(p1, NULL);
    28	    Pthread_join(p2, NULL);
    29	    printf("Final value   : %d\n", counter);
    30	    return 0;
    31	}
$
     
$ ./threads 10
Initial value : 0
Final value   : 20
$ ./threads 100
Initial value : 0
Final value   : 200
$ ./threads 1000
Initial value : 0
Final value   : 2000
$ ./threads 10000
Initial value : 0
Final value   : 19897
$ ./threads 10000
Initial value : 0
Final value   : 15562
$ ./threads 10000
Initial value : 0
Final value   : 14179
$ ./threads 100000
Initial value : 0
Final value   : 103750