Facebook
From Buff Madrill, 4 Years ago, written in C#.
This paste is a reply to ss from Antek - go back
Embed
Viewing differences between ss and Re: ss
#include 
#include 
#include 
#include h>
#include 
#include 
#include 
#define SHARE  1
sem_t id;     //...identyfikator używanego semafora
int n;          //zmienna globalna na której działać będą wątki


void* thread( void *ptr )
{
    int i = *((int *) ptr); //...z argumentu pobierzemy numer kolejny wątku
    printf( "wątek %d: start\n",i );

    sem_wait( &id );    //...wątek wykonuje P(), wyłączność 
    printf( "wątek %d: krytyczna, start\n",i );
    printf( "wątek %d: n = %d\n",i,n );
    printf( "wątek %d: n++\n",i ); n++;
    printf( "wątek %d: n = %d\n",i,n );
    printf( "wątek %d: krytyczna, stop\n",i );
    sem_post( &id );        //...wątek wykonuje V(), zwolnienie  

    printf( "wątek %d: stop\n",i );
    pthread_exit( 0 );
}

int main( int argc,char** argv )
{
     sem_t *id;
 pid_t child;
 
int i[]={1,2};      //tablica numerów wątków
    pthread_t first,second; 
    sem_init( &id,!SHARE,1 );   //...tworzymysemafor (POSIX, nienazwany)
    // wątki startują
    pthread_create( &first,  NULL,thread,(void *)(i+0) );
    pthread_create( &second, NULL,thread,(void *)(i+1) );
    /* tutaj pracują wątki */ 
    pthread_join( first,NULL 
status;
 id = sem_open( "szlaban",O_CREAT,S_IRUSR|S_IWUSR,0 );
 switch( (int)(child=fork()) )
 {
 case -1: perror("...fork()..."); exit( 1 
); pthread_join(second,NULL );
    // wątki zakończyły działanie
    sem_destroy( &id );     //semafor usunięty
    return 0;
break;
case 0: ...kod dla potomka
printf("*** [%u] potomek czeka na semafor (%p)\n",(unsigned)getpid(),id);
sem_wait( id );
printf( "*** [%u] potomek zakończył\n",(unsigned)getpid() );
exit( 0 );
default: ...kod dla procesu nadrzędnego
printf( "*** [%u] ustawia semafor (%p)\n",(unsigned)getpid(),id );
sem_post( id );
if( !wait( &status ) ){ perror( "... wait()..." ); exit( 2 ); }
else
{
printf( "*** [%u] wygląda, że to wszystko\n",(unsigned)getpid() );
sem_close( id ); sem_unlink( "szlaban" );
}
}
 return 0;
}

Replies to Re: ss rss

Title Name Language When
Re: Re: ss Colossal Bushbaby csharp 4 Years ago.