我一直在听C++中的仿函数.有人可以给我一个关于它们是什么的概述以及在什么情况下它们会有用吗?
相关问题:
关于C++ 11:
关于Boost:
我如何获得一个线程池,以任务发送到,而无需创建和删除它们一遍又一遍?这意味着要在不加入的情况下重新同步的持久线程.
我的代码看起来像这样:
namespace {
std::vector<std::thread> workers;
int total = 4;
int arr[4] = {0};
void each_thread_does(int i) {
arr[i] += 2;
}
}
int main(int argc, char *argv[]) {
for (int i = 0; i < 8; ++i) { // for 8 iterations,
for (int j = 0; j < 4; ++j) {
workers.push_back(std::thread(each_thread_does, j));
}
for (std::thread &t: …Run Code Online (Sandbox Code Playgroud) 我有一个程序,其函数将指针作为arg和main.主要是创建n个线程,每个线程根据传递的内容在不同的内存区域运行arg.然后连接线程,主要在区域之间执行一些数据混合,并创建n个新线程,这些线程执行与旧线程相同的操作.
为了改进程序,我想保持线程活着,消除创建它们所需的长时间.线程应在主要工作时休眠,并在必须再次出现时通知.同样,主要应该在线程工作时等待,就像连接一样.
我无法最终实现这一点,总是陷入僵局.
简单的基线代码,任何有关如何修改它的提示将非常感激
#include <thread>
#include <climits>
...
void myfunc(void * p) {
do_something(p);
}
int main(){
void * myp[n_threads] {a_location, another_location,...};
std::thread mythread[n_threads];
for (unsigned long int j=0; j < ULONG_MAX; j++) {
for (unsigned int i=0; i < n_threads; i++) {
mythread[i] = std::thread(myfunc, myp[i]);
}
for (unsigned int i=0; i < n_threads; i++) {
mythread[i].join();
}
mix_data(myp);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我已经浏览了Stack Overflow并且已经有了一些非常好的答案,(我的代码实际上基于这里的答案)但是由于某种原因我得到了奇怪的行为 - 因为thread_func应该被称为ls1次,但它在线程退出之前仅运行0到2次.似乎ioService.stop()在完成排队的作业之前就已经将其排除,但据我所知,这不应该发生.以下是相关的代码段:
boost::asio::io_service ioService;
boost::asio::io_service::work work(ioService);
boost::thread_group threadpool;
for (unsigned t = 0; t < num_threads; t++)
{
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
}
//Iterate over the dimensions of the matrices
for (unsigned i = 0; i < ls1; i++)
{
ioService.post(boost::bind(&thread_func,i, rs1, rs2, ls2, arr, left_arr, &result));
}
ioService.stop();
threadpool.join_all();
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,谢谢!