Subject: Re: posix semaphores and libpthread
To: None <jdolecek@netbsd.org>
From: Anthony Mallet <anthony.mallet@laas.fr>
List: current-users
Date: 02/02/2003 21:42:15
Jaromir Dolecek wrote :
| Since you are using nonshared semaphore and sem_wait(), how'd
| you ever get wakeup from the call?

From a signal and SIGALRM. I attach a sample code below.

| I assume that the semaphore is nonshared by seeing that
| you hit the preempt condition, which is only hit for USEM_USER
| semaphores. USEM_USER is set when sem_init() is called
| with pshared == 0, so I'm assuming you do just that. If you
| expect the semaphore to be posted from other process, you
| ought to sem_init() it with pshared == 1 ...

Yup, I call it with pshared = 0.
The following code works if I create a dummy thread before the sem_wait
call.

#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/time.h>

sem_t		sem;

void		timer_func(int);

int
main()
{
   pthread_t		thread;
   struct itimerval	tv;
   int			status;

   status = sem_init(&sem, 0, 0);
   if (status) { perror("sem_init"); return 2; }

   /* prepare for receiving SIGALRM */
   signal(SIGALRM, timer_func);

   /* setup a timer that starts after 1s */
   tv.it_interval.tv_usec = 0;
   tv.it_interval.tv_sec = 0;
   tv.it_value.tv_usec = 0;
   tv.it_value.tv_sec = 1;

   status = setitimer(ITIMER_REAL, &tv, NULL);
   if (status) { perror("setitimer"); return 2; }

   /* block on the condition variable */
   printf("before sem_wait\n");
   sem_wait(&sem);
   printf("after sem_wait\n");

   return 0;
}

/* SIGALRM handler */
void
timer_func(int dummy)
{
   printf("before sem_post\n");
   sem_post(&sem);
   printf("after sem_post\n");
}