#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#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 )
{
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 ); pthread_join(second,NULL );
// wątki zakończyły działanie
sem_destroy( &id ); //semafor usunięty
return 0;
}
Replies to ss 
Title |
Name |
Language |
UNIX |
When |
Re: ss |
Buff Madrill |
csharp |
1606344332 |
4 Years ago. |
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}