summaryrefslogtreecommitdiffstats
path: root/lib/libc_r/thread/thread_storage.c
blob: fa8357c85ec4135b53e23f817655c7dc1896f784 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* libpthread's stronger functions */

#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include "pthread_private.h"

void
_libc_private_storage_lock(mutex)
        pthread_mutex_t *mutex;
{
	if (__isthreaded && pthread_mutex_lock(mutex) != 0)
		PANIC("_libc_private_storage_lock");
}

void
_libc_private_storage_unlock(mutex)
        pthread_mutex_t *mutex;
{
	if (__isthreaded && pthread_mutex_unlock(mutex) != 0)
		PANIC("_libc_private_storage_unlock");
}

void *
_libc_private_storage(volkey, init, initsz, error)
	volatile struct _thread_private_key_struct * volkey;
	void *	init;
	size_t	initsz;
	void *	error;
{
	void *result;
	void (*cleanfn)(void *);
	struct _thread_private_key_struct * key;

	/* Use static storage while not threaded: */
	if (!__isthreaded)
		return init;

	key = (struct _thread_private_key_struct *)volkey;	/* for gcc */

	/* Create the key once: */
	if (volkey->once.state == PTHREAD_NEEDS_INIT) {
		if (pthread_mutex_lock(&key->once.mutex) != 0)
			return error;
		if (volkey->once.state == PTHREAD_NEEDS_INIT) {
			if (key->cleanfn == NULL)
				cleanfn = free;
			else
				cleanfn = key->cleanfn;
			if (pthread_key_create(&key->key, cleanfn) != 0) {
				pthread_mutex_unlock(&key->once.mutex);
				return error;
			}
			key->once.state = PTHREAD_DONE_INIT;
		}
		pthread_mutex_unlock(&key->once.mutex);
	}

	/* XXX signals may cause re-entrancy here? */

	/* Acquire this key's thread-specific storage: */
	result = pthread_getspecific(key->key);

	/* Allocate and initialise storage if unallocated: */
	if (result == NULL) {
		result = malloc(initsz);
		if (result == NULL)
			return error;
		if (pthread_setspecific(key->key, result) != 0) {
			free(result);
			return error;
		}
		memcpy(result, init, initsz);
	}

	return result;
}