我目前正在尝试使用 Apache Portable Runtime 实现线程。一切正常,但由于缺乏文档或示例,我不确定我是否按照预期的方式进行操作。
我需要两个线程和信号处理来捕获控制台上的 CTRL-C 来清理我的服务器和可能的线程。这是我目前的做法:
// 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;
}
这或多或少符合预期。我唯一不确定的是清理工作是否正常。
清理功能似乎被调用不止一次(字符串“Caught signal..”在终端上出现不止一次)。有没有办法防止这种情况?这有问题吗?
我发现了不止一个使用后清理 APR 线程的示例。我的方式是否足够或者我需要一些评论的东西?还是我完全错了?