1#include "../Mutex.h"
2#include "../Thread.h"
3#include <vector>
4#include <boost/shared_ptr.hpp>
5#include <stdio.h>
6
7using namespace muduo;
8
9class Foo
10{
11 public:
12  void doit() const;
13};
14
15typedef std::vector<Foo> FooList;
16typedef boost::shared_ptr<FooList> FooListPtr;
17FooListPtr g_foos;
18MutexLock mutex;
19
20void post(const Foo& f)
21{
22  printf("post\n");
23  MutexLockGuard lock(mutex);
24  if (!g_foos.unique())
25  {
26    g_foos.reset(new FooList(*g_foos));
27    printf("copy the whole list\n");
28  }
29  assert(g_foos.unique());
30  g_foos->push_back(f);
31}
32
33void traverse()
34{
35  FooListPtr foos;
36  {
37    MutexLockGuard lock(mutex);
38    foos = g_foos;
39    assert(!g_foos.unique());
40  }
41
42  // assert(!foos.unique()); this may not hold
43
44  for (std::vector<Foo>::const_iterator it = foos->begin();
45      it != foos->end(); ++it)
46  {
47    it->doit();
48  }
49}
50
51void Foo::doit() const
52{
53  Foo f;
54  post(f);
55}
56
57int main()
58{
59  g_foos.reset(new FooList);
60  Foo f;
61  post(f);
62  traverse();
63}
64
65