Boost logo

Boost Users :

From: Sam Partington (Sam.Partington_at_[hidden])
Date: 2003-05-13 09:29:52


William E. Kempf wrote:
> Actually, we can, and do in the thread_dev branch. It means that the
> ID is of implementation defined type, but it's portable.

In the mean time I would probably do something like the following:
(obviously it needs a bit of fleshing out)

template<class T> class thread_map
{
 class wrapper;
public:
 typedef const wrapper* id;

 id create(const boost::function1<void, id> &f, const T& data)
 {
  boost::mutex::scoped_lock lock(m);
  threads.push_back(boost::shared_ptr<wrapper>(new wrapper(f)));
  return ids.insert(std::make_pair(threads.back().get(),
data)).first->first;
 }

 T& operator[](id x)
 {
  boost::mutex::scoped_lock lock(m);
  std::map<id, T>::iterator i(ids.find(x));
  if (i == ids.end())
   throw std::out_of_range("Thread ID does not exist");
  return i->second;
 }

private:
 class wrapper : boost::noncopyable
 {
  boost::thread t;
 public:
  explicit wrapper(boost::function1<void, id> f)
   : t(boost::bind<void>(f, this))
  {}
 };
 boost::mutex m;
 std::map<id, T> ids;
 std::vector<boost::shared_ptr<wrapper> > threads;
};

void mythread(thread_map<int>::id id) { /* do something */ }

void f()
{
 thread_map<int> threads;
 thread_map<int>::id id(threads.create(&mythread, 42));
 DEBUG_ASSERT(threads[id] == 42);
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net