#include <pthread.h> #include <stdio.h>/* this function is run By the first thread */void *inc_x (void *x_void_ptr) { printf ("Thread xxxxxxxxxxxxxxxxxxxxxxx start \ n"); /* increment x to 100 */ int *x_ptr = (int *) x_void_ptr; while (+ + (*x_ptr) < 100) { printf ("Thread x: %d\n", &NBSP;*X_PTR); } printf ("Thread xxxxxxxxxxxxxxxxxxxxxxx end \ n"); /* the function must return something - null will do */ return null;} /* this function is run by the second thread */void *inc_y ( VOID&NBSP;*Y_VOID_PTR) { printf ("thread yyyyyyyyyyyyyyyyyyyyyy start\ n "); /* increment x to 100 */ int *y_ptr = (int *) Y_void_ptr; while (+ + (*y_ptr) < 100) { printf ("Thread y: %d\n", *y_ptr); } printf ("Thread yyyyyyyyyyyyyyyyyyyyyy end \ n"); /* the function must return something - null will do */ return null;} Int main () { int x = 0, y = 0; /* show the initial values of x and y */ printf ("x: %d, y: %d\n", x, y); /* this variable is our reference to the first thread */ pthread_t&nBsp;inc_x_thread; /* this variable is our reference to the second thread */ pthread_t inc_y_thread; /* create a first thread which executes inc_x (&x) */ if (Pthread_create (&inc_x_thread, null, inc_x, &x)) { fprintf (stderr, "error creating thread\n"); return 1; } /* create a second thread which executes inc_x (&x) */ if (Pthread_create (&inc_y_thread, null, inc_y, &y)) { fprintf (stderr, "error creating thread\n"); return 1; } /* wait for the second Thread to finish */ if (Pthread_join (inc_x_thread, null)) { fprintf (stderr, "error joining thread\n"); return 2; } if (Pthread_join (inc_y_thread, null)) { fprintf ( stderr, "error joining thread\n"); return 2 ; } /* show the results - x is now 100 thanks to the second thread */ printf ( "x: %d, y: %d\n", x, y); return 0;}
The simplest example of c-pthread multithreading