uThreads  0.3.0
uThreadCache.h
1 /*******************************************************************************
2  * Copyright © 2015, 2016 Saman Barghi
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  *******************************************************************************/
17 
18 #ifndef UTHREADS_CACHE_H_
19 #define UTHREADS_CACHE_H_
20 
21 #include <mutex>
22 #include "../generic/IntrusiveContainers.h"
23 #include "uThread.h"
24 
33 class uThreadCache {
34 
35 private:
36  //global mutex for protecting the underlying data structure
37  std::mutex mtx;
38  IntrusiveStack<uThread> stack;
39  size_t count;
40  size_t size;
41 
42 public:
43  uThreadCache(size_t size = defaultuThreadCacheSize) : count(0), size(size){};
44  ~uThreadCache(){}
45 
56  ssize_t push(uThread* ut){
57  std::unique_lock<std::mutex> mlock(mtx, std::try_to_lock);
58  //do not block just to grab this lock
59  if(!mlock.owns_lock() || count == size) return -1;
60  ut->reset();
61  stack.push(*ut);
62  return ++count;
63  }
64 
70  std::unique_lock<std::mutex> mlock(mtx, std::try_to_lock);
71  //do not block just to grab this lock
72  if(!mlock.owns_lock() || count == 0) return nullptr;
73  count--;
74  return stack.pop();
75  }
76 };
77 
78 #endif /* UTHREADS_CACHE_H_ */
Data structure to cache uThreads.
Definition: uThreadCache.h:33
uThread * pop()
pop a uThread from the list in FIFO order and return it
Definition: uThreadCache.h:69
user-level threads (fiber)
Definition: uThread.h:63
ssize_t push(uThread *ut)
adds a uThread to the cache
Definition: uThreadCache.h:56