user2971678
user2971678

Reputation: 47

Put function into template

I found a thread pool class and i tried with alot of combinations to call method with function inside.

Here is example of my try :

WorkerPool wp(4);
wp.run_task<Connection::On_NET1_LOGIN>(&On_NET1_LOGIN());

Here are the WorkerPool's functions :

 template < typename Task >
  void run_task( Task task )
  {
    boost::unique_lock< boost::mutex > lock( mutex_ );

    // If no threads are available, then return.
    if ( 0 == available_ ) return;

    // Decrement count, indicating thread is no longer available.
    --available_;

    // Post a wrapped task into the queue.
    io_service_.post( boost::bind( &WorkerPool::wrap_task, this,
                                   boost::function< void() >( task ) ) );
  }

private:
  /// @brief Wrap a task so that the available count can be increased once
  ///        the user provided task has completed.
  void wrap_task( boost::function< void() > task )
  {
    // Run the user supplied task.
    try
    {
      task();
    }
    // Suppress all exceptions.
    catch ( ... ) {}

    // Task has finished, so increment count of available threads.
    boost::unique_lock< boost::mutex > lock( mutex_ );
    ++available_;
  }

What I doing wrong in calling function to that threadpool ? Thanks.

Upvotes: 0

Views: 64

Answers (1)

Agentlien
Agentlien

Reputation: 5116

You are trying to add the task like this:

wp.run_task<Connection::On_NET1_LOGIN>(&On_NET1_LOGIN());

It seems there are two issues with this.

  1. You do not need to specify template parameters, as they can be inferred. Also, if you did, you should specify the type - not the name - of the function.
  2. You want to pass the address of the function to be called, but you are trying to call the function and take the address of the result.

To solve both these issues, try the following:

wp.run_task(&Connection::On_NET1_LOGIN);

Note: Since On_NET1_LOGIN seems to be a member function of Connection, this won't work unless the function is static. If this is not the case, you need a Connection instance to call the function on and you need to send a function object which does this. This can be solved using a lambda or std::bind.

Upvotes: 1

Related Questions