CopyOnWrite_test.cc revision e9c0c409
12d3b4de6SShuo Chen#include "../Mutex.h"
22d3b4de6SShuo Chen#include "../Thread.h"
32d3b4de6SShuo Chen#include <vector>
42d3b4de6SShuo Chen#include <boost/shared_ptr.hpp>
52d3b4de6SShuo Chen#include <stdio.h>
62d3b4de6SShuo Chen
72d3b4de6SShuo Chenusing namespace muduo;
82d3b4de6SShuo Chen
92d3b4de6SShuo Chenclass Foo
102d3b4de6SShuo Chen{
112d3b4de6SShuo Chen public:
122d3b4de6SShuo Chen  void doit() const;
132d3b4de6SShuo Chen};
142d3b4de6SShuo Chen
152d3b4de6SShuo Chentypedef std::vector<Foo> FooList;
162d3b4de6SShuo Chentypedef boost::shared_ptr<FooList> FooListPtr;
172d3b4de6SShuo ChenFooListPtr g_foos;
182d3b4de6SShuo ChenMutexLock mutex;
192d3b4de6SShuo Chen
202d3b4de6SShuo Chenvoid post(const Foo& f)
212d3b4de6SShuo Chen{
222d3b4de6SShuo Chen  printf("post\n");
232d3b4de6SShuo Chen  MutexLockGuard lock(mutex);
242d3b4de6SShuo Chen  if (!g_foos.unique())
252d3b4de6SShuo Chen  {
262d3b4de6SShuo Chen    g_foos.reset(new FooList(*g_foos));
272d3b4de6SShuo Chen    printf("copy the whole list\n");
282d3b4de6SShuo Chen  }
292d3b4de6SShuo Chen  assert(g_foos.unique());
302d3b4de6SShuo Chen  g_foos->push_back(f);
312d3b4de6SShuo Chen}
322d3b4de6SShuo Chen
332d3b4de6SShuo Chenvoid traverse()
342d3b4de6SShuo Chen{
352d3b4de6SShuo Chen  FooListPtr foos;
362d3b4de6SShuo Chen  {
372d3b4de6SShuo Chen    MutexLockGuard lock(mutex);
382d3b4de6SShuo Chen    foos = g_foos;
392d3b4de6SShuo Chen    assert(!g_foos.unique());
402d3b4de6SShuo Chen  }
412d3b4de6SShuo Chen
42e9c0c409SShuo Chen  // assert(!foos.unique()); this may not hold
43e9c0c409SShuo Chen
442d3b4de6SShuo Chen  for (std::vector<Foo>::const_iterator it = foos->begin();
452d3b4de6SShuo Chen      it != foos->end(); ++it)
462d3b4de6SShuo Chen  {
472d3b4de6SShuo Chen    it->doit();
482d3b4de6SShuo Chen  }
492d3b4de6SShuo Chen}
502d3b4de6SShuo Chen
512d3b4de6SShuo Chenvoid Foo::doit() const
522d3b4de6SShuo Chen{
532d3b4de6SShuo Chen  Foo f;
542d3b4de6SShuo Chen  post(f);
552d3b4de6SShuo Chen}
562d3b4de6SShuo Chen
572d3b4de6SShuo Chenint main()
582d3b4de6SShuo Chen{
592d3b4de6SShuo Chen  g_foos.reset(new FooList);
602d3b4de6SShuo Chen  Foo f;
612d3b4de6SShuo Chen  post(f);
622d3b4de6SShuo Chen  traverse();
632d3b4de6SShuo Chen}
642d3b4de6SShuo Chen
65