2 * Server-side semaphore management
4 * Copyright (C) 1998 Alexandre Julliard
13 #include "server/process.h"
14 #include "server/thread.h"
18 struct object obj
; /* object header */
19 unsigned int count
; /* current count */
20 unsigned int max
; /* maximum possible count */
23 static void semaphore_dump( struct object
*obj
, int verbose
);
24 static int semaphore_signaled( struct object
*obj
, struct thread
*thread
);
25 static int semaphore_satisfied( struct object
*obj
, struct thread
*thread
);
26 static void semaphore_destroy( struct object
*obj
);
28 static const struct object_ops semaphore_ops
=
43 struct object
*create_semaphore( const char *name
, unsigned int initial
, unsigned int max
)
45 struct semaphore
*sem
;
47 if (!max
|| (initial
> max
))
49 SET_ERROR( ERROR_INVALID_PARAMETER
);
52 if (!(sem
= (struct semaphore
*)create_named_object( name
, &semaphore_ops
, sizeof(*sem
) )))
54 if (GET_ERROR() != ERROR_ALREADY_EXISTS
)
56 /* initialize it if it didn't already exist */
63 int open_semaphore( unsigned int access
, int inherit
, const char *name
)
65 return open_object( name
, &semaphore_ops
, access
, inherit
);
68 int release_semaphore( int handle
, unsigned int count
, unsigned int *prev_count
)
70 struct semaphore
*sem
;
72 if (!(sem
= (struct semaphore
*)get_handle_obj( current
->process
, handle
,
73 SEMAPHORE_MODIFY_STATE
, &semaphore_ops
)))
76 *prev_count
= sem
->count
;
77 if (sem
->count
+ count
< sem
->count
|| sem
->count
+ count
> sem
->max
)
79 SET_ERROR( ERROR_TOO_MANY_POSTS
);
84 /* there cannot be any thread waiting if the count is != 0 */
85 assert( !sem
->obj
.head
);
91 wake_up( &sem
->obj
, count
);
93 release_object( sem
);
97 static void semaphore_dump( struct object
*obj
, int verbose
)
99 struct semaphore
*sem
= (struct semaphore
*)obj
;
100 assert( obj
->ops
== &semaphore_ops
);
101 fprintf( stderr
, "Semaphore count=%d max=%d name='%s'\n",
102 sem
->count
, sem
->max
, get_object_name( &sem
->obj
) );
105 static int semaphore_signaled( struct object
*obj
, struct thread
*thread
)
107 struct semaphore
*sem
= (struct semaphore
*)obj
;
108 assert( obj
->ops
== &semaphore_ops
);
109 return (sem
->count
> 0);
112 static int semaphore_satisfied( struct object
*obj
, struct thread
*thread
)
114 struct semaphore
*sem
= (struct semaphore
*)obj
;
115 assert( obj
->ops
== &semaphore_ops
);
116 assert( sem
->count
);
118 return 0; /* not abandoned */
121 static void semaphore_destroy( struct object
*obj
)
123 struct semaphore
*sem
= (struct semaphore
*)obj
;
124 assert( obj
->ops
== &semaphore_ops
);