我的代码是:
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 111\n");
if (thread_barcode_open == 0)
{
printf("create_timeThread 222\n");
quit_barcode_flag = 0;
ret = pthread_create(&idtb, NULL, (void *)thread_Barcode, NULL);
printf("create_timeThread 333\n");
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 444\n");
}
void quit_BarcodeThread(void)
{
printf("quit_timeThread\n");
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?
答案 0 :(得分:1)
尽管最佳做法是使用select
,但您最好的选择是使用pthread_cancel
。只需在调用idtb
之前在pthread_join
上调用它,它就会向线程发送一个信号,要求它停止,执行所有清理工作。