From: Marc Cromme Date: Sun, 9 Oct 2005 19:53:37 +0000 (+0000) Subject: session mutex and id counter made static, now many instances of a Session object... X-Git-Tag: YP2.0.0.2~228 X-Git-Url: http://git.indexdata.com/?a=commitdiff_plain;h=f05f2c3cb62b12590abf370d1681ed80fb1626d5;p=metaproxy-moved-to-github.git session mutex and id counter made static, now many instances of a Session object do increment the same global static counter. This has the advantage that a worker just can create it's own static object. --- diff --git a/src/session.hpp b/src/session.hpp index c157ffd..504bb14 100644 --- a/src/session.hpp +++ b/src/session.hpp @@ -2,8 +2,7 @@ #ifndef SESSION_HPP #define SESSION_HPP -#include - +//#include #include @@ -12,7 +11,8 @@ namespace yp2 { class Session { public: - Session() : m_id(0){}; + //Session() {}; + /// returns next id, global state of id protected by boost::mutex long unsigned int id() { boost::mutex::scoped_lock scoped_lock(m_mutex); @@ -20,21 +20,27 @@ namespace yp2 { return m_id; }; private: - /// disabled because class is singleton - Session(const Session &); + // disabled because class is singleton + // Session(const Session &); - /// disabled because class is singleton - Session& operator=(const Session &); + // disabled because class is singleton + // Session& operator=(const Session &); - boost::mutex m_mutex; - unsigned long int m_id; + /// static mutex to lock static m_id + static boost::mutex m_mutex; + + /// static m_id to make sure that there is only one id counter + static unsigned long int m_id; }; - - } +// initializing static members +boost::mutex yp2::Session::m_mutex; +unsigned long int yp2::Session::m_id = 0; + + #endif /* * Local variables: diff --git a/src/test_session2.cpp b/src/test_session2.cpp index 2a7a8ba..876aac6 100644 --- a/src/test_session2.cpp +++ b/src/test_session2.cpp @@ -17,13 +17,13 @@ boost::mutex io_mutex; class Worker { public: - Worker(yp2::Session *session, int nr = 0) - : m_session(session), m_nr(nr){}; + Worker(int nr = 0) + : m_nr(nr){}; void operator() (void) { for (int i=0; i < 100; ++i) { - m_id = m_session->id(); + m_id = m_session.id(); //print(); } } @@ -36,7 +36,7 @@ class Worker } private: - yp2::Session *m_session; + yp2::Session m_session; int m_nr; int m_id; }; @@ -48,19 +48,21 @@ BOOST_AUTO_TEST_CASE( testsession2 ) // test session try { - yp2::Session session; - const int num_threads = 10; + const int num_threads = 100; boost::thread_group thrds; + yp2::Session session; + for (int i=0; i < num_threads; ++i) { - Worker w(&session, i); + // Notice that each Worker has it's own session object! + Worker w(i); thrds.add_thread(new boost::thread(w)); } thrds.join_all(); - BOOST_CHECK (session.id() == 1001); + BOOST_CHECK (session.id() == 10001); } catch (std::exception &e) {