source: trunk/test/queue.cc @ 3057

Last change on this file since 3057 was 3057, checked in by Peter, 10 years ago

New class: multithread safe queue

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 1.7 KB
Line 
1// $Id: queue.cc 3057 2013-07-01 05:38:07Z peter $
2
3/*
4  Copyright (C) 2013 Peter Johansson
5
6  This file is part of the yat library, http://dev.thep.lu.se/yat
7
8  The yat library is free software; you can redistribute it and/or
9  modify it under the terms of the GNU General Public License as
10  published by the Free Software Foundation; either version 3 of the
11  License, or (at your option) any later version.
12
13  The yat library is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with yat. If not, see <http://www.gnu.org/licenses/>.
20*/
21
22#include <config.h>
23
24#include "Suite.h"
25
26#include "yat/utility/Queue.h"
27
28#include <boost/thread.hpp>
29
30#include <iostream>
31
32using namespace theplu::yat;
33using utility::Queue;
34
35class Worker
36{
37public:
38  Worker(Queue<std::string>& q)
39  : queue_(q) {}
40
41  void operator()(void)
42  {
43    std::string str = " ";
44    while (str.size()) {
45      queue_.pop(str);
46      if (str.size()) {
47        queue_.push(str.substr(1));
48        if (str.size()>1)
49          queue_.push(str.substr(0,str.size()-1));
50      }
51      sleep(1);
52      // Make sure we can be interrupted
53      boost::this_thread::interruption_point();
54    }
55  }
56
57private:
58  Queue<std::string>& queue_;
59};
60
61int main(int argc,char* argv[])
62{
63  test::Suite suite(argc, argv);
64  Queue<std::string> queue;
65  queue.push("Peter");
66
67  boost::thread_group workers;
68  workers.create_thread(Worker(queue));
69  workers.create_thread(Worker(queue));
70  workers.create_thread(Worker(queue));
71  workers.create_thread(Worker(queue));
72
73  workers.join_all();
74
75  std::cerr << "OK\n";
76  return 0;
77}
Note: See TracBrowser for help on using the repository browser.