2011-04-22 57 views
0

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; 
} 

回答

3

如果你有一些其他的機制來指示程序的結束和只有你使用getchar()的原因是阻止,所以你不會結束程序,那麼你根本就不需要它。

你可以在main中使用pthread_join()進程線程。 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; 
} 
0

這是做到這一點的方式。如果您不想阻止等待的getchar()返回時,可以使用的kbhit的Linux版本():

http://pwilson.net/kbhit.html