linux gcc c89處理pthread乾淨出口
目前我有一個事件循環,將捕獲和處理事件。這個事件循環將在自己的線程中運行,該線程由主函數創建。出於測試目的,我在這個循環中使用了一個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;
}