【发布时间】: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;
}
【问题讨论】: