Facebook
From Antek, 4 Years ago, written in C.
Embed
Download Paste or View Raw
Hits: 79
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <semaphore.h>
  6. #define SHARE  1
  7. sem_t id;     //...identyfikator używanego semafora
  8. int n;          //zmienna globalna na której działać będą wątki
  9.  
  10.  
  11. void* thread( void *ptr )
  12. {
  13.     int i = *((int *) ptr); //...z argumentu pobierzemy numer kolejny wątku
  14.     printf( "wątek %d: start\n",i );
  15.  
  16.     sem_wait( &id );    //...wątek wykonuje P(), wyłączność
  17.     printf( "wątek %d: krytyczna, start\n",i );
  18.     printf( "wątek %d: n = %d\n",i,n );
  19.     printf( "wątek %d: n++\n",i ); n++;
  20.     printf( "wątek %d: n = %d\n",i,n );
  21.     printf( "wątek %d: krytyczna, stop\n",i );
  22.     sem_post( &id );        //...wątek wykonuje V(), zwolnienie  
  23.  
  24.     printf( "wątek %d: stop\n",i );
  25.     pthread_exit( 0 );
  26. }
  27.  
  28. int main( int argc,char** argv )
  29. {
  30.     int i[]={1,2};      //tablica numerów wątków
  31.     pthread_t first,second;
  32.     sem_init( &id,!SHARE,1 );   //...tworzymysemafor (POSIX, nienazwany)
  33.     // wątki startują
  34.     pthread_create( &first,  NULL,thread,(void *)(i+0) );
  35.     pthread_create( &second, NULL,thread,(void *)(i+1) );
  36.     /* tutaj pracują wątki */
  37.     pthread_join( first,NULL ); pthread_join(second,NULL );
  38.     // wątki zakończyły działanie
  39.     sem_destroy( &id );     //semafor usunięty
  40.     return 0;
  41. }
  42.  

Replies to ss rss

Title Name Language When
Re: ss Buff Madrill csharp 4 Years ago.