Semaphore: Difference between revisions

1,405 bytes added ,  8 years ago
m
no edit summary
(API section (like for mutexes) + Ada implementation)
mNo edit summary
 
(5 intermediate revisions by 3 users not shown)
Line 11:
=Sample implementations / APIs=
 
=={{header|[[Ada}}]]==
Here is an implementation of a semaphore based on protected objects. The implementation provides operations P (seize) and V (release), these names are usually used with semaphores.
<lang ada>
protected type Semaphore (K : Positive) is
entry P;
Line 20:
Count : Natural := K;
end Mutex;
</adalang>
The implementation of:
<lang ada>
protected body Semaphore is
entry P when Count > 0 is
Line 33:
end V;
end Semaphore;
</adalang>
Use:
<lang ada>
declare
S : Semaphore (5);
Line 51:
S.V; -- Release it
end;
</adalang>
It is also possible to implement semaphore as a monitor task.
 
=={{header|C}}==
{{libheader|pthread}}
 
Here is an example of counting semaphores in C, using the "pthread" library. To make the code more readable, no error checks are made. A productive version of this implementation should check all the return values from the various function calls!
 
The example is divided into two parts: the "Interface" (usually the content of a *.h file)...
<lang c>
//
// Interface
//
typedef struct Sema *Sema;
 
Sema Sema_New (int init);
void Sema_P (Sema s);
void Sema_V (Sema s);
</lang>
... and the "Implementation" (the *.c file):
<lang c>
//
// Implementation
//
#include <stdlib.h>
#include <pthread.h>
 
struct Sema {
int value;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
};
 
Sema Sema_New (int init) {
Sema s;
 
s = malloc (sizeof (*s));
s->value = init;
s->mutex = malloc (sizeof (*(s->mutex)));
s->cond = malloc (sizeof (*(s->cond)));
pthread_mutex_init (s->mutex, NULL);
pthread_cond_init (s->cond, NULL);
 
return s;
}
 
void Sema_P (Sema s) {
pthread_mutex_lock (s->mutex);
while (s->value == 0) {
pthread_cond_wait (s->cond, s->mutex);
}
s->value--;
pthread_mutex_unlock (s->mutex);
}
 
void Sema_V (Sema s) {
pthread_mutex_lock (s->mutex);
s->value++;
if (s->value == 1) {
pthread_cond_signal (s->cond);
}
pthread_mutex_unlock (s->mutex);
}
</lang>
Anonymous user