2017.9.6
F函数需要处理不定时来的数据,且不知道调用者如何处理这些数据。因此,将处理这些数据的函数,以函数指针的方式,作为实参传递给F,由调用者决定处理这些数据所使用的函数。
一个简单的例子
2019.10.18
在线程中循环调用回调函数
- 头文件
#include <thread>
#include <unistd.h>
void loop(void (*f)(int)) {
int num = 0;
for(int i = 0; i < 1000; ++i) {
for(int j = 0; j < 1000000; ++j) {
num++;
}
sleep(1);
f(num);
}
}
void survey(void (*f)(int)) {
std::thread th(loop, f);
th.detach();
}
- 源文件
#include "thread_callback.h"
#include <iostream>
#include <sys/time.h>
void p(int num) {
struct timeval start, end;
gettimeofday(&start, NULL);
std::cout << num << std::endl;
gettimeofday(&end, NULL);
float cost_time = (end.tv_usec-start.tv_usec)/1000000.0 + end.tv_sec-start.tv_sec;
std::cout << cost_time << std::endl;
}
void test() {
survey(p);
}
int main() {
// survey(p);
test();
std::cout << "cost_time" << std::endl;
sleep(36000);
return 0;
}
- 线程使用detach()方法,主函数不sleep会导致所有线程退出,test函数是为了证明线程间是平级的,test执行完,loop仍继续执行。主函数结束导致所有线程退出是因为它会通知系统结束进程中的所有线程。