-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_specific.hpp
More file actions
84 lines (69 loc) · 1.89 KB
/
Copy paththread_specific.hpp
File metadata and controls
84 lines (69 loc) · 1.89 KB
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
79
80
81
82
83
84
/* Any copyright is dedicated to the Public Domain.
* https://creativecommons.org/publicdomain/zero/1.0/ */
#pragma once
#include <pthread.h>
#include <cassert>
namespace ft
{
template <typename T>
class thread_specific_ptr
{
private:
static void default_deleter(T* ptr)
{
delete ptr;
}
public:
typedef T element_type;
typedef void (*deleter_type)(T*);
typedef ::pthread_key_t* native_handle_type;
typedef void (*native_deleter_type)(void*);
private:
::pthread_key_t key;
deleter_type deleter;
public:
explicit thread_specific_ptr(deleter_type deleter = &default_deleter)
: deleter(deleter)
{
assert(::pthread_key_create(&this->key, reinterpret_cast<native_deleter_type>(deleter)) == 0);
}
~thread_specific_ptr()
{
assert(::pthread_key_delete(this->key) == 0);
}
T* get() const
{
return static_cast<T*>(::pthread_getspecific(this->key));
}
T* operator->() const
{
return this->get();
}
T& operator*() const
{
return *this->get();
}
T* release()
{
T* const value = this->get();
assert(::pthread_setspecific(this->key, NULL) == 0);
return value;
}
void reset(T* new_value = NULL)
{
T* const value = this->get();
if (value != new_value)
{
(*this->deleter)(value);
assert(::pthread_setspecific(this->key, new_value) == 0);
}
}
native_handle_type native_handle()
{
return &this->key;
}
private:
thread_specific_ptr(thread_specific_ptr&);
thread_specific_ptr& operator=(thread_specific_ptr&);
};
}