/* * ===================================================================================== * * Filename: simple_tests.cpp * * Description: * * Version: 1.0 * Created: 2021年03月30日 11时29分40秒 * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include "util.h" struct s1000 { char a[1000]; }; BOOST_AUTO_TEST_CASE(BasicTest) { const std::string shm_name("basic"); ShmRemover auto_remove(shm_name); SharedMemory shm(shm_name, 1024 * 1024 * 10); auto Avail = [&]() { return shm.get_free_memory(); }; auto init_avail = Avail(); auto BasicTest = [&](int tid, int nloop) { auto Code = [&](int id) { typedef NamedShmObject Int; std::string name = std::to_string(id); auto a0 = Avail(); Int i1(shm, name, eOpenOrCreate); auto a1 = Avail(); BOOST_CHECK_LT(a1, a0); printf("s1000 size: %ld\n", a0 - a1); i1->a[0] = 5; Int i2(shm, name, eOpenOrCreate); auto a2 = Avail(); BOOST_CHECK_EQUAL(a1, a2); BOOST_CHECK_EQUAL(i1.data(), i2.data()); int i = i1.Remove(); BOOST_CHECK_EQUAL(Avail(), a0); { auto old = Avail(); void *p = shm.Alloc(1024); shm.Dealloc(p); BOOST_CHECK_EQUAL(old, Avail()); } bool r = shared_memory_object::remove(shm_name.c_str()); BOOST_CHECK(r); }; for (int i = 0; i < nloop; ++i) { Code(i + tid * nloop); } }; // boost::timer::auto_cpu_timer timer; ThreadManager threads; int nthread = 1; int nloop = 1; for (int i = 0; i < nthread; ++i) { threads.Launch(BasicTest, i, nloop); } BOOST_CHECK_EQUAL(init_avail, Avail()); } BOOST_AUTO_TEST_CASE(ForkTest) { ProcessManager procs; const int nproc = 10; printf("Testing fork:\n"); auto child = [&](int id) { std::this_thread::sleep_for(100ms * id); printf("child id: %3d/%d ends\r", id, nproc); }; for (int i = 0; i < nproc; ++i) { procs.Launch(child, i + 1); } } BOOST_AUTO_TEST_CASE(RefCountTest) { SharedMemory &shm = TestShm(); typedef MsgI Msg; GlobalInit(shm); Msg m0(1000, shm); BOOST_CHECK(!m0.valid()); m0.Make(100); BOOST_CHECK_EQUAL(m0.Count(), 1); Msg m1 = m0; BOOST_CHECK(m1.valid()); BOOST_CHECK_EQUAL(m1.AddRef(), 2); BOOST_CHECK_EQUAL(m0.AddRef(), 3); BOOST_CHECK_EQUAL(m0.Release(), 2); BOOST_CHECK_EQUAL(m0.Release(), 1); BOOST_CHECK_EQUAL(m1.Release(), 0); BOOST_CHECK(!m1.valid()); }