#include #include #include #include #define NUM_THREADS 2 // gcc -lpthread -o thread-example thread-example.c int global = 6; char buf[] = "a write to standard output\n"; int var = 88; void *thread( void *thread_id ) { int *id_ptr, taskid; id_ptr = ( int * ) thread_id; taskid = *id_ptr; if ( taskid == 0 ) { ++global; ++var; } else sleep( 2 ); printf( "pid = %d, taskid = %d, global = %d, var = %d\n", getpid(), taskid, global, var ); pthread_exit( NULL ); } int main( void ) { pthread_t threads[ NUM_THREADS ]; int t, rc; if ( write( STDOUT_FILENO, buf, sizeof (buf) - 1 ) != sizeof( buf ) - 1 ) { fprintf( stderr, "write error" ); exit( 1 ); } printf( "before pthread_create()\n" ); for ( t = 0; t < NUM_THREADS; ++t ) { rc = pthread_create( &threads[t], NULL, thread, ( void * ) &t ); if ( rc ) { printf ( "ERROR; return code from pthread_create() is %d\n", rc ); exit( -1 ); } } sleep( 3 ); printf( "pid = %d, global = %d, var = %d\n", getpid(), global, var ); pthread_exit( NULL ); }