Subject: POSIX threads and RT extensions - can they co-exist ?
To: None <tech-userlevel@netbsd.org>
From: Ian Zagorskih <ianzag@megasignal.com>
List: tech-userlevel
Date: 06/08/2004 17:58:40
NetBSD IANZAG 2.0_BETA NetBSD 2.0_BETA (IANZAG) #0: Thu Jun  3 20:54:46 NOVST 
2004  ianzag@IANZAG:/usr/src/sys/arch/i386/compile/IANZAG i386

In short - application core dumps when:
1) linked with -lrt and -lpthread
2) inits and waits for POSIX unnamed semaphore
3) does not create any thread

I have the following simple test program which uses both pthreads and unnamed 
semaphores:

---main.c---
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void *thread(void *);

sem_t sem_sync;
pthread_t pth;

int
main(int argc, char *argv[])
{
	int rc;

	rc = sem_init(&sem_sync, 0, 0);
	if (rc == -1) {
		perror("sem_init");
		return EXIT_FAILURE;
	}

	#if 0
	rc = pthread_create(&pth, NULL, thread, NULL);
	if (rc) {
		perror("pthread_create");
		return EXIT_FAILURE;
	}
	#endif

	while (1) {
		sem_wait(&sem_sync);
		printf("main wait\n");
	}

	return EXIT_SUCCESS;
}

void *
thread(void *arg)
{
	struct timespec ts;
	int left = 5;

	while (left-- > 0) {
		sem_post(&sem_sync);
		ts.tv_sec = 1;
		ts.tv_nsec = 0;
		nanosleep(&ts, NULL);
	}

	return NULL;
}
---main.c---

---Makefile---
PROG=	test01
SRCS=	main.c
LDADD+=	-lrt -lpthread
WARNS=	3
MKMAN=	no

.include <bsd.prog.mk>
---Makefile---

This app core dumps when i
1) link binary image with -lpthread
2) init semaphore with pshared = 0
3) wait for this semaphore

$ ./test01
assertion "next != 0" failed: file "/usr/src/lib/libpthread/pthread_run.c", 
line 130, function "pthread__next"
Abort (core dumped)

$ ident /usr/src/lib/libpthread/pthread_run.c
/usr/src/lib/libpthread/pthread_run.c:
     $NetBSD: pthread_run.c,v 1.17 2004/03/14 01:19:42 cl Exp $
     $NetBSD: pthread_run.c,v 1.17 2004/03/14 01:19:42 cl Exp $

All is fine when i do not link agains -lpthread or when semaphore is created 
with pshared = 1 or when i create any thread before waiting and so on.

AFAIU pthread library intercepts RT calls. But why it manually fails on 
sem_wait() when there's no threads ? I, for example, can create unnamed 
non-shared semaphore and wait for it in the main process, trigger it from 
signal handler and only after this seq call pthread_create().

Any ideas ?

// wbr