【问题标题】:processing pthread for clean exit处理 pthread 以干净退出
【发布时间】:2011-04-22 08:06:11
【问题描述】:

linux gcc c89

目前我有一个事件循环来捕获和处理事件。这个事件循环将在它自己的线程中运行,该线程是从主函数创建的。出于测试目的,我在此循环中使用了 usleep。

我有一个条件 app_running 来控制循环并退出循环。

但是,当我运行我的应用程序时,我不想退出 main,因为这会终止应用程序。所以我有一个 getchar() 来等待输入以指示我要终止应用程序。这会将 app_running 设置为 false 以退出事件循环。这一切看起来有点便宜。不使用 getchar() 有没有更好的方法?

非常感谢您的任何建议,

标题

#ifndef NETWORK_TASKS_H_INCLUDED
#define NETWORK_TASKS_H_INCLUDED

#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif

int app_running;

void* process_events(void);

#endif /* NETWORK_TASKS_H_INCLUDED */

实施

#include <stdio.h>
#include <unistd.h>

#include "network_tasks.h"

void* process_events(void)
{
    app_running = TRUE;

    while(app_running) {
#define TIMEOUT 3000000
        /* This will be used for capturing events. use usleep for simulating testing */
        /* if(net_events(TIMEOUT) != 0) { */
        /*     process_network_event(); */
        /* } */
        /* Just for testing */
        usleep(TIMEOUT);
        printf("Sleeping.....\n");
    }

    printf("Finished sleeping....\n");

    return NULL;
}

主要

#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>

#include "network_tasks.h"

int main(void)
{
    pthread_t th_id = 0;
    int th_rc = 0;

    th_rc = pthread_create(&th_id, NULL, (void*)process_events, NULL);

    if(th_rc == -1) {
        fprintf(stderr, "Cannot create thread [ %s ]\n", strerror(errno));
        return -1;
    }

    getchar();
    app_running = FALSE;

    pthread_exit(NULL);

    return 0;
}

【问题讨论】:

    标签: c pthreads posix


    【解决方案1】:

    如果您有一些其他机制来指示程序结束,并且您使用 getchar() 的唯一原因是阻塞,因此您不会结束程序,那么您根本不需要它。

    你可以 pthread_join() main 中的进程线程。 Main 将阻塞该调用,直到进程线程完成。

    或者,如果您在 main 中没有进一步的工作要做,您可以简单地使用 pthread_exit()。与 exit() 不同,pthread_exit() 不会杀死所有其他正在运行的线程。

    另外,您对 pthread_create() 的返回码检查编码不正确。 Pthreads 在错误约定上背离了标准的 unix 返回码 -1。成功时返回 0,出错时返回正整数代码。

    int main(void)
    {
        pthread_t th_id;
        int th_rc;
    
        th_rc = pthread_create(&th_id, NULL, (void*)process_events, NULL);
    
        if(th_rc != 0) 
        {
            fprintf(stderr, "Cannot create thread [ %s ]\n", strerror(th_rc));
            return -1;
        }
    
        th_rc = pthread_join(th_id, NULL);
    
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      这就是这样做的方法。如果你不想阻塞等待 getchar() 返回,你可以使用 linux 版本的 kbhit():

      http://pwilson.net/kbhit.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-01
        • 1970-01-01
        • 2011-08-29
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多