gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:33:52 25 4
gpt4 key购买 nike

我有一个机器人,我通过特定的 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;

最佳答案

根据man页面:

The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable.

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

关于c - C 中的线程只是停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com