在子线程完成执行之前,主线程似乎没有执行

时间:2018-04-13 04:36:04

标签: c linux pthreads

每次计时器到期时都会引发标志,并创建一个线程来执行一些特殊任务,让主任务继续执行任务而不会中断(正如我在预期输出中所示:)。但正如您在实际输出中所看到的,创建线程时主要任务已停止,但线程需要非常长的时间(超过20秒)才能完成。由于主线程处于无限循环中(虽然它在函数之间切换),我认为我不应该使用 pthread_join()。发生了什么,我该怎么做才能获得预期的产出?

int global_flag, thread_exist;
void main() {
    //background time, on timer expire, execute "timer_signal_handler" 
    create_timer(tim_value=60sec, tim_interval=60sec);
    int val = 0;
    while(1){
        val = random_integer_generator();
        function_fun(val);
    }
    return; 
}
void function_fun(int val) {
    if(global_flag == 1 && thread_exist == 0) {
        global_flag = 0;
        pthread_t pid_port_scan;
            if ((pthread_create (&pid_port_scan, NULL, portScanRoutine, NULL)) != 0) {
            perror("pthread_create: ");
            thread_exist = 0;
            exit(EXIT_FAILURE);
            }
            else thread_exist = 1;
    }
    printf("value %d\n", val);
    return;
}
void *portScanRoutine(void* ptr) {
    printf("started scanning...\n");
    printf("scanning in progress...\n");
    scan_for_ports_whick_takes_around_20_to_30_seconds;
    printf("done scanning...\n");
    thread_exist = 0;
    return;
}
void timer_signal_handler(int sigId) {
    printf("timer expied\n");
    global_flag = 1;//set to indicate
}

actual Output:
value x//x is random value
value x
value x
value x
value x
value x
timer expied
started scanning...
scanning in progress...
done scanning...
value x
value x
value x
value x
value x
timer expied
started scanning...
scanning in progress...
done scanning...
value x
value x
value x



expected output:
value x//x is random value
value x
value x
value x
value x
value x
timer expied
started scanning...
scanning in progress...
value x
value x
value x
value x
value x
value x
done scanning...
value x
value x
value x

0 个答案:

没有答案
相关问题