diff options
author | David Robillard <d@drobilla.net> | 2012-05-14 04:30:00 +0000 |
---|---|---|
committer | David Robillard <d@drobilla.net> | 2012-05-14 04:30:00 +0000 |
commit | 79deafe642561936ebb3bbcf585f2c6f26b456d3 (patch) | |
tree | 896f4486237286d09440399c25c50ca97e940636 /raul/ThreadVar.hpp | |
parent | 52e92126896c9d4e2ed2e0f3db7dd70809a473d6 (diff) | |
download | raul-79deafe642561936ebb3bbcf585f2c6f26b456d3.tar.gz raul-79deafe642561936ebb3bbcf585f2c6f26b456d3.tar.bz2 raul-79deafe642561936ebb3bbcf585f2c6f26b456d3.zip |
Remove Thread context stuff and add a thread-specific variable class, ThreadVar, which can be used for this and many other things.
ClientBroadcaster => Broadcaster.
git-svn-id: http://svn.drobilla.net/lad/trunk/raul@4405 a436a847-0d15-0410-975c-d299462d15a1
Diffstat (limited to 'raul/ThreadVar.hpp')
-rw-r--r-- | raul/ThreadVar.hpp | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/raul/ThreadVar.hpp b/raul/ThreadVar.hpp new file mode 100644 index 0000000..54e0d4e --- /dev/null +++ b/raul/ThreadVar.hpp @@ -0,0 +1,70 @@ +/* + This file is part of Raul. + Copyright 2007-2012 David Robillard <http://drobilla.net> + + Raul is free software: you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or any later version. + + Raul is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Raul. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef RAUL_THREADVAR_HPP +#define RAUL_THREADVAR_HPP + +#include <stdlib.h> +#include <pthread.h> + +namespace Raul { + +struct ThreadVarImpl; + +/** Thread-specific variable. + */ +template<typename T> +class ThreadVar +{ +public: + ThreadVar(const T& default_value) + : _default_value(default_value) + { + pthread_key_create(&_key, free); + } + + ~ThreadVar() { + pthread_key_delete(_key); + } + + ThreadVar& operator=(const T& value) { + T* val = (T*)pthread_getspecific(_key); + if (val) { + *val = value; + } else { + val = (T*)malloc(sizeof(value)); + *val = value; + pthread_setspecific(_key, val); + } + return *this; + } + + operator T() const { + T* val = (T*)pthread_getspecific(_key); + return val ? *val : _default_value; + } + +private: + ThreadVar(const ThreadVar& noncopyable); + ThreadVar& operator=(const ThreadVar& noncopyable); + + const T _default_value; + pthread_key_t _key; +}; + +} // namespace Raul + +#endif // RAUL_THREADVAR_HPP |