繁体   English   中英

使用不同的参数函数运行std :: thread

[英]Running std::thread with different argument function

是否可以创建N个std :: thread对象,每个对象运行一个while循环,直到“任务”列表不为空?

可能看起来像这样:

Schedule sched( N );
schned.add( func1, param1, param2, param3 );
schned.add( func1, param1, param2, param3 );

schned.add( func2, param1 );

schned.add( func3, IntegerParam );
schned.add( func4, StringParam );

sched.start(); // start & join each thread wait until all threads finished

带有函数声明:

bool func1( int, int, int );
bool func2( int );
bool func3( int );
bool func4( std::string );

可变参数可能吗?

只要所有函数都具有相同的返回类型,这对于std::bindstd::function应该非常简单。

在您的Schedule类中,您可以只存储一个std::queue<std::function<bool()>> 然后让Schedule::add()看起来像这样:

template<typename func>
Schedule::add(func f) {
    // Appropriate synchronization goes here...
    function_queue.push_front(f);  // Will work as long as func can be converted to std::function<bool()>
}

然后,您可以添加如下任务:

Shedule sched(N);
// This works with function pointers
sched.add(someFunctionThatTakesNoArgs);
// And function like objects such as those returned by std::bind
sched.add(std::bind(func1, param1, param2, param3));
sched.add(std::bind(func1, param1, param2, param3));
sched.add(std::bind(func2, param1));
// Even member functions
SomeClass foo;
sched.add(std::bind(SomeClass::func3, foo, IntegerParam));
sched.add(std::bind(SomeClass::func4, foo, StringParam));

sched.start();

然后让您的工作线程执行以下操作:

Schedule::worker() {
    // Synchronization left as an exercise for the reader...
    while (more_work_to_do) {
        std::function<bool()> f(function_queue.pop_back());
        f();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM