#ifndef SESSION_HPP
#define SESSION_HPP
-#include <stdexcept>
-
+//#include <stdexcept>
#include <boost/thread/mutex.hpp>
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);
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:
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();
}
}
}
private:
- yp2::Session *m_session;
+ yp2::Session m_session;
int m_nr;
int m_id;
};
// 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) {