C - 如何立即退出 pthread



我的代码是:

int check_barcode_flag = 1;
pthread_t idtb = -2;
static int thread_barcode_open = 0;
int quit_barcode_flag = 0;
int result = 0;
int scan_fd = -1;
void thread_Barcode(){
    char barcode[SCN_BCD_SZ];
    char code[SCN_BCD_SZ];
    int i = 0;
    struct input_event ev;
    char *device = "/dev/event1";
    int rd;
    char mtemp[128];
    scan_fd = open(device, O_RDONLY);
    if (scan_fd == -1) {
        printf("Failed to open event device.n");
        huy_debug_com_opened("Failed to open event device.");
        exit(1);
    }
    huy_debug_com_opened("open event device.");
    while (1){      
        if (quit_barcode_flag == 1)
        {
            huy_debug_com_opened("huhuhu why?");
            break;
        }
        read(scan_fd, &ev, sizeof(struct input_event));
        if (ev.type == 1 && ev.value == 1){
            if (ev.code != 28 && ev.code != 0 && ev.code != 42)
            {
                code[i++] = keycodelist(ev.code);                           
            }           
            if (ev.code == 28){
                WM_ClrLine(LINE4, LINE7);
                sprintf(Barcode_Code, "%s", code);
                WM_DispString(NULL, Barcode_Code, LINE4, 0, LEFT_DISP, NORMAL_DISP);
                sprintf(mtemp, "BARCODE = %s", code);
                i = 0;
                memset(code, 0, SCN_BCD_SZ);                
            }
        }
    }
}
void create_BarcodeThread(void)
{
    int ret;
    printf("create_timeThread  111n");
    if (thread_barcode_open == 0)
    {
        printf("create_timeThread  222n");
        quit_barcode_flag = 0;
        ret = pthread_create(&idtb, NULL, (void *)thread_Barcode, NULL);
        printf("create_timeThread  333n");
        if (ret != 0)
            printf("Create pthread error!n");
        else
        {
            check_barcode_flag = 1;
            thread_barcode_open = 1;
            printf("Create pthread success!n");
        }
    }
    printf("create_timeThread  444n");
}
void quit_BarcodeThread(void)
{
    printf("quit_timeThreadn");
    quit_barcode_flag = 1;
    if (thread_barcode_open)
    {
        pthread_join(idtb, NULL);
    }
    idtb = -2;
    thread_barcode_open = 0;
}

main()中,我用create_BarcodeThread()创建了pthread。 我用我的设备扫描条形码没问题。之后,我调用quit_BarcodeThread()退出线程,但read(scan_fd, &ev, sizeof(struct input_event))正在等待,我无法立即退出线程。 我必须扫描条形码才能read()运行,然后quit_barcode_flag == 1,现在我断线。

如何read()不是等待,或者我可以立即退出 pthread?

尽管这样做的最佳做法是使用 select ,但下一个最佳选择是使用 pthread_cancel 。 只需在调用pthread_join之前idtb调用它,它就会向线程发送一个信号,要求它停止,并尽可能执行所有清理。

最新更新