#include <pthread.h>
#include <string.h>

#define NODEFINE
#include <u.h>
#include <libc.h>
#include <fcall.h>

static pthread_key_t upkey;
extern pthread_mutex_t pm_rendlock;

void
pm_threadinit(void)
{
	char buf[512];
	int err;
	Pmproc *p;

	if(pthread_key_create(&upkey, nil))
		pm_sysfatal("pm_threadinit: key_create failed");
	
	p = pm_mallocz(sizeof(*p), 1);
	if(p == nil)
		pm_sysfatal("allocate first Pmproc failed");
		
	if(pthread_setspecific(upkey, p))
		pm_sysfatal("pm_threadinit: setspecific failed");

	if((err = pthread_mutex_init(&pm_rendlock, NULL)) != 0){
		pm_snprint(buf, sizeof buf, "mutex_init rendlock: %s", strerror(err));
		pm_panic(buf);
	}
}

static Pmproc theproc;

Pmproc*
pm_getup(void)
{
	Pmproc *p;

	if((p = pthread_getspecific(upkey)) == nil)
		pm_panic("pm_getup");
	return p;
}

void
pm_setup(Pmproc *p)
{
	if(pthread_setspecific(upkey, p) != 0)
		pm_panic("pm_setup");
}
