queue.cpp

An example of the thread queue class. This may be relevant to producer- consumer scenarios and realtime applications where queued messages are stored on a re-usable object pool.

00001 // Copyright (C) 2010 David Sugar, Tycho Softworks.
00002 //
00003 // This file is part of GNU uCommon C++.
00004 //
00005 // GNU uCommon C++ is free software: you can redistribute it and/or modify
00006 // it under the terms of the GNU Lesser General Public License as published
00007 // by the Free Software Foundation, either version 3 of the License, or
00008 // (at your option) any later version.
00009 //
00010 // GNU uCommon C++ is distributed in the hope that it will be useful,
00011 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 // GNU Lesser General Public License for more details.
00014 //
00015 // You should have received a copy of the GNU Lesser General Public License
00016 // along with GNU uCommon C++.  If not, see <http://www.gnu.org/licenses/>.
00017 
00018 #ifndef DEBUG
00019 #define DEBUG
00020 #endif
00021 
00022 #include <ucommon/ucommon.h>
00023 
00024 #include <stdio.h>
00025 
00026 using namespace UCOMMON_NAMESPACE;
00027 
00028 static unsigned reused = 0;
00029 
00030 class myobject : public ReusableObject
00031 {
00032 public:
00033     unsigned count;
00034 
00035     myobject()
00036         {count = ++reused;};
00037 };
00038 
00039 static mempager pool;
00040 static paged_reuse<myobject> myobjects(&pool, 100);
00041 static queueof<myobject> mycache(&pool, 10);
00042 
00043 extern "C" int main()
00044 {
00045     unsigned i;
00046 
00047     myobject *x;
00048     for(i = 0; i < 10; ++i) {
00049         x = myobjects.create();
00050         mycache.post(x);
00051     }
00052     assert(x->count == 10);
00053 
00054     for(i = 0; i < 3; ++i) {
00055         x = mycache.lifo();
00056         assert(x != NULL);
00057     }
00058     assert(x->count == 8);
00059 
00060     init<myobject>(x);
00061     assert(x->count == 11);
00062 
00063     for(i = 0; i < 3; ++i) {
00064         x = mycache.lifo();
00065         assert(x != NULL);
00066         myobjects.release(x);
00067     }
00068 
00069     x = init<myobject>(NULL);
00070     assert(x == NULL);
00071     assert(reused == 11);
00072     return 0;
00073 }
00074 

Generated on 14 Aug 2013 for UCommon by  doxygen 1.4.7