thread.c 2.43 KB
Newer Older
1 2 3 4 5 6 7
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

8
#include "git2_util.h"
9

10
#if !defined(GIT_THREADS)
11

12
#define TLSDATA_MAX 16
13

14 15 16 17 18 19 20 21 22
typedef struct {
	void *value;
	void (GIT_SYSTEM_CALL *destroy_fn)(void *);
} tlsdata_value;

static tlsdata_value tlsdata_values[TLSDATA_MAX];
static int tlsdata_cnt = 0;

int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
23
{
24 25
	if (tlsdata_cnt >= TLSDATA_MAX)
		return -1;
26

27 28 29 30 31
	tlsdata_values[tlsdata_cnt].value = NULL;
	tlsdata_values[tlsdata_cnt].destroy_fn = destroy_fn;

	*key = tlsdata_cnt;
	tlsdata_cnt++;
32 33 34 35

	return 0;
}

36
int git_tlsdata_set(git_tlsdata_key key, void *value)
37
{
38 39 40 41
	if (key < 0 || key > tlsdata_cnt)
		return -1;

	tlsdata_values[key].value = value;
42 43 44
	return 0;
}

45
void *git_tlsdata_get(git_tlsdata_key key)
46
{
47 48 49 50
	if (key < 0 || key > tlsdata_cnt)
		return NULL;

	return tlsdata_values[key].value;
51 52
}

53
int git_tlsdata_dispose(git_tlsdata_key key)
54
{
55 56
	void *value;
	void (*destroy_fn)(void *) = NULL;
57

58 59
	if (key < 0 || key > tlsdata_cnt)
		return -1;
60

61 62
	value = tlsdata_values[key].value;
	destroy_fn = tlsdata_values[key].destroy_fn;
63

64 65
	tlsdata_values[key].value = NULL;
	tlsdata_values[key].destroy_fn = NULL;
66

67 68
	if (value && destroy_fn)
		destroy_fn(value);
69

70
	return 0;
71 72
}

73 74 75
#elif defined(GIT_WIN32)

int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
76
{
77
	DWORD fls_index = FlsAlloc(destroy_fn);
78

79
	if (fls_index == FLS_OUT_OF_INDEXES)
80 81
		return -1;

82
	*key = fls_index;
83 84 85
	return 0;
}

86
int git_tlsdata_set(git_tlsdata_key key, void *value)
87
{
88
	if (!FlsSetValue(key, value))
89 90 91 92 93
		return -1;

	return 0;
}

94
void *git_tlsdata_get(git_tlsdata_key key)
95
{
96
	return FlsGetValue(key);
97 98
}

99
int git_tlsdata_dispose(git_tlsdata_key key)
100
{
101 102 103 104
	if (!FlsFree(key))
		return -1;

	return 0;
105 106 107 108
}

#elif defined(_POSIX_THREADS)

109
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
110
{
111
	if (pthread_key_create(key, destroy_fn) != 0)
112 113 114 115 116
		return -1;

	return 0;
}

117
int git_tlsdata_set(git_tlsdata_key key, void *value)
118
{
119
	if (pthread_setspecific(key, value) != 0)
120 121 122 123 124
		return -1;

	return 0;
}

125
void *git_tlsdata_get(git_tlsdata_key key)
126
{
127
	return pthread_getspecific(key);
128 129
}

130
int git_tlsdata_dispose(git_tlsdata_key key)
131
{
132 133 134 135
	if (pthread_key_delete(key) != 0)
		return -1;

	return 0;
136 137 138
}

#else
139
# error unknown threading model
140
#endif