C中的线程只是停止执行?

时间:2019-01-20 18:03:56

标签: c

我有一个机器人,可以使用C通过特定的库进行控制。

我需要一个线程来检查是否按下了按钮,如果按下,则程序退出。

此检查应与主线程分开进行,以便我可以运行机器人运动代码以及按钮检查代码。

我做了一个小的PoC,但是它不起作用:程序流停止并且无限期地执行按钮检查。

这是代码。如果此代码段中缺少某些变量/函数,请放心,它们在实际代码中。

void *brick_controller(void *vargp){
    printf("Second thread is working!\n");
    uint8_t button_buffer;
    while(true)
    {
        size_t result = ev3_read_keys(&button_buffer);
        //printf("ass %d\n", buf);
        if(button_buffer == 32){
            exit(666);
        }
    }
}

int main(int argc, char** argv)
{
    printf( "Waiting the EV3 brick online...\n" );
    if ( ev3_init() < 1 ) return ( 1 );

    printf( "*** ( EV3 ) Hello! ASS ***\n" );
    ev3_sensor_init();
    ev3_tacho_init();

    app_alive = app_init();
    if (app_alive == 0)
    {
        /*int distance = 250;
        if (argc == 1)
        {} 
        else if (argc == 2)
        {
            default_speed = atoi(argv[1]);
        } 
        else if (argc == 3)
        {
            default_speed = atoi(argv[1]);
            distance = atoi(argv[2]);
        }
        else {
            printf("Too many arguments!\n");
            return 0;
        }

        printf("Speed:%d\n"
                "Distance:%d\n", default_speed, distance);
        drive(default_speed, distance);
        */
        pthread_create(&brick_controller_thread, NULL, *brick_controller, NULL); 
        pthread_join(brick_controller_thread, NULL); 

        int i = 0;
        while(i < 200){ // This never executes :(
            i++;
            printf("All is running! %d\n", i); 
        }

    } else {
        printf("App initialization failed! Error code: %d\n", app_alive);
        return 2;
    }

    ev3_uninit();
    return 0;

1 个答案:

答案 0 :(得分:3)

根据man页:

  

pthread_join()函数等待线程指定的线程          终止。如果该线程已经终止,则          pthread_join()立即返回。线程指定的线程          必须可以加入。

pthread_join等待线程终止,但永远不会终止。