我目前正在尝试使用实现线程。一切都很好,除了我不太确定我是否按照它的方式去做,因为缺乏文档或例子。
我需要两个线程和信号处理来在控制台上捕获一个CTRL来清理我的服务器,可能还有线程。这是我目前的做法:
// Define APR thread pool
apr_pool_t *pool;
// Define server
MyServer *server;
// Define threads
apr_thread_t *a_thread, *b_thread;
apr_status_t status;
static void * APR_THREAD_FUNC func_a(apr_thread_t * thread,
void *data) {
// do func_a stuff here
}
static void * APR_THREAD_FUNC func_b(apr_thread_t * thread,
void *data) {
// do func_b stuff here
}
// Cleanup before exit
void cleanup(int s) {
printf("Caught signal %d\n", s);
// Destroy thread pool
apr_pool_destroy(pool);
//apr_thread_exit(a_thread, APR_SUCCESS);
//apr_thread_exit(b_thread, APR_SUCCESS);
//apr_terminate();
// Stop server and cleanup
server->stopServer();
delete server;
exit(EXIT_SUCCESS);
}
int main(void) {
// Signal handling
signal(SIGINT, cleanup);
// Create server
server = MyServerFactory::getServerImpl();
bool success = server->startServer();
// Initialize APR
if (apr_initialize() != APR_SUCCESS) {
printf("Could not initialize\n");
return EXIT_FAILURE;
}
// Create thread pool
if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
printf("Could not allocate pool\n");
return EXIT_FAILURE;
}
// Create a_thread thread
if (apr_thread_create(&a_thread, NULL, func_a, NULL,
pool) != APR_SUCCESS) {
printf("Could not create a_thread\n");
return EXIT_FAILURE;
}
//Create b_thread thread
if (apr_thread_create(&b_thread, NULL, func_b, NULL,
pool) != APR_SUCCESS) {
printf("Could not create b_thread\n");
return EXIT_FAILURE;
}
// Join APR threads
apr_thread_join(&status, a_thread);
apr_thread_join(&status, b_thread);
return EXIT_SUCCESS;
}这或多或少地如预期的那样工作。我唯一不确定的是清理工作是否正常。
发布于 2018-04-10 17:29:23
APR线程清理在螺纹段 of APR教程中有相当详细的解释。按照顺序,清理步骤如下所示:
apr_thread_exit()。当Unix线程自动终止时,Windows线程不会终止。为可移植性调用此函数(并在必要时返回状态)。apr_thread_join()等待所有线程的终止。apr_pool_destroy()来释放主内存池。(使用apr_thread_exit()释放子内存池。)apr_terminate()释放其他资源(套接字等)。注意,只需在另一个线程中调用exit(),而不需要执行最后的步骤可能导致崩溃。他们也有一个简单样例程序来演示其中的一些东西。
至于为什么你的信号处理程序两次开火,我不认为这与APR有关。SIGINT被发送到父进程和子进程,因此我怀疑MyServer正在分叉一个新进程,两者都在调用处理程序。
https://stackoverflow.com/questions/14192219
复制相似问题