Qucs-S S-parameter Viewer & RF Synthesis Tools
Loading...
Searching...
No Matches
TThreadStateCreator.hpp
1#ifndef GREENLET_THREAD_STATE_CREATOR_HPP
2#define GREENLET_THREAD_STATE_CREATOR_HPP
3
4#include <ctime>
5#include <stdexcept>
6
7#include "greenlet_internal.hpp"
8#include "greenlet_refs.hpp"
9#include "greenlet_thread_support.hpp"
10
11#include "TThreadState.hpp"
12
13namespace greenlet {
14
15
16typedef void (*ThreadStateDestructor)(ThreadState* const);
17
18// Only one of these, auto created per thread as a thread_local.
19// Constructing the state constructs the MainGreenlet.
20template<ThreadStateDestructor Destructor>
22{
23private:
24 // Initialized to 1, and, if still 1, created on access.
25 // Set to 0 on destruction.
26 ThreadState* _state;
27 G_NO_COPIES_OF_CLS(ThreadStateCreator);
28
29 inline bool has_initialized_state() const noexcept
30 {
31 return this->_state != (ThreadState*)1;
32 }
33
34 inline bool has_state() const noexcept
35 {
36 return this->has_initialized_state() && this->_state != nullptr;
37 }
38
39public:
40
42 _state((ThreadState*)1)
43 {
44 }
45
47 {
48 if (this->has_state()) {
49 Destructor(this->_state);
50 }
51
52 this->_state = nullptr;
53 }
54
55 inline ThreadState& state()
56 {
57 // The main greenlet will own this pointer when it is created,
58 // which will be right after this. The plan is to give every
59 // greenlet a pointer to the main greenlet for the thread it
60 // runs in; if we are doing something cross-thread, we need to
61 // access the pointer from the main greenlet. Deleting the
62 // thread, and hence the thread-local storage, will delete the
63 // state pointer in the main greenlet.
64 if (!this->has_initialized_state()) {
65 // XXX: Assuming allocation never fails
66 this->_state = new ThreadState;
67 // For non-standard threading, we need to store an object
68 // in the Python thread state dictionary so that it can be
69 // DECREF'd when the thread ends (ideally; the dict could
70 // last longer) and clean this object up.
71 }
72 if (!this->_state) {
73 throw std::runtime_error("Accessing state after destruction.");
74 }
75 return *this->_state;
76 }
77
78 operator ThreadState&()
79 {
80 return this->state();
81 }
82
83 operator ThreadState*()
84 {
85 return &this->state();
86 }
87
88 inline int tp_traverse(visitproc visit, void* arg)
89 {
90 if (this->has_state()) {
91 return this->_state->tp_traverse(visit, arg);
92 }
93 return 0;
94 }
95
96};
97
98
99
100}; // namespace greenlet
101
102#endif
Definition TThreadStateCreator.hpp:22
Definition TThreadState.hpp:87
Definition __init__.py:1