首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >APR线程和信号处理

APR线程和信号处理
EN

Stack Overflow用户
提问于 2013-01-07 08:24:38
回答 1查看 1.5K关注 0票数 4

我目前正在尝试使用实现线程。一切都很好,除了我不太确定我是否按照它的方式去做,因为缺乏文档或例子。

我需要两个线程和信号处理来在控制台上捕获一个CTRL来清理我的服务器,可能还有线程。这是我目前的做法:

代码语言:javascript
复制
// 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;
}

这或多或少地如预期的那样工作。我唯一不确定的是清理工作是否正常。

  1. 清理函数似乎被调用不止一次(字符串“捕获信号.”)。在终端上出现不止一次)。有什么办法可以防止这种情况发生吗?这有问题吗?
  2. 我在使用后发现了不止一个清理APR线程的例子。我的方法足够了吗?还是我需要一些评论?还是我完全错了?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-10 17:29:23

APR线程清理在螺纹段 of APR教程中有相当详细的解释。按照顺序,清理步骤如下所示:

  1. 在线程本身中调用apr_thread_exit()。当Unix线程自动终止时,Windows线程不会终止。为可移植性调用此函数(并在必要时返回状态)。
  2. 在主线程中调用apr_thread_join()等待所有线程的终止。
  3. 调用apr_pool_destroy()来释放主内存池。(使用apr_thread_exit()释放子内存池。)
  4. 调用apr_terminate()释放其他资源(套接字等)。注意,只需在另一个线程中调用exit(),而不需要执行最后的步骤可能导致崩溃

他们也有一个简单样例程序来演示其中的一些东西。

至于为什么你的信号处理程序两次开火,我不认为这与APR有关。SIGINT被发送到父进程和子进程,因此我怀疑MyServer正在分叉一个新进程,两者都在调用处理程序。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14192219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档