Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass function of classe #22

Open
LeMoussel opened this issue Mar 1, 2019 · 3 comments
Open

How to pass function of classe #22

LeMoussel opened this issue Mar 1, 2019 · 3 comments

Comments

@LeMoussel
Copy link

LeMoussel commented Mar 1, 2019

I have this class

 class MyTask
 {
 public:
 	// Function to be executed by thread function
 	void run()
 	{
 		std::cout << "Task Start" << std::endl;
 
 		// Check if thread is requested to stop ?
 		while (stopRequested() == false)
 		{
 			std::cout << "Doing Some Work" << std::endl;
 			std::this_thread::sleep_for(std::chrono::milliseconds(1000));
 
 		}
 		std::cout << "Task End" << std::endl;
 	}
 };

I do
MyTask task; ctpl::thread_pool testThreadPool(4);

How can I push task.run() to ctpl::thread_pool?
testThreadPool.push(task.run);, isn't correct

@pemsley
Copy link

pemsley commented Mar 1, 2019

task.run() needs to be static.

@armallen
Copy link

I was able to do such a thing without using static. Just do something like this:

    const std::function<void(int, MyTask&)> wrapMyTaskRun([&] (int id, MyTask & t) -> void
            {
                t.run();
            });

Then you can push to the thread pool:

MyTask task;
ctpl::thread_pool testThreadPool(4);
testThreadPool->push(wrapMyTaskRun, task);

I don't know if it is the optimal way to do this, but it works for me.

@nicolas-chan-42
Copy link

If you read the example.cpp carefully, you should see that there is an int id argument in every function passed into the thread pool.

Just add an int id into the argument of your run() and then you should be able to push it, i.e.
void run(int id) in your code of class.
And then you can push it using testThreadPool.push(task.run);

I don't know why, but CTPL requires all functions being pushed into the thread pool having an int argument as its first argument, regardless of the number of arguments actually used in the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants