使用 C 中的线程在循环时获取用户输入而不会阻塞



我想在 while 循环中从用户那里获取一个值,即变量的设定值,而不会阻止要执行的其他任务。我正在尝试使用线程,我的试用导致失败。即使我正在使用 pthread,该程序也被scanf函数阻止。

这就是我在main()函数中创建pthread的方式

uint16_t refAngle = 0;
char refAngleString[64];
int main(void)
{
pthread_t thread_id;
while(1) {
pthread_create(&thread_id, NULL, threadUserInput, NULL);
pthread_join(thread_id, NULL);
// Other functions were called below ...
}
}

然后我有一个名为threadUserInput的线程函数

void *threadUserInput(void* vargp)
{
scanf("%s", refAngleString);
refAngle = (uint16_t) atoi(refAngleString);
printf("Angle is: %dn", refAngle);
return NULL;
}

任何帮助将不胜感激,提前感谢。

即使我正在使用 pthread,该程序也被 scanf 函数阻止。

是的。 创建的线程在scanf()中被阻塞,而父线程在pthread_join()中被阻塞,等待另一个线程。 我很难想出任何启动单个线程然后立即加入它的充分理由,而不是简单地直接调用线程函数。

如果要在循环的每次迭代中获取一次用户输入,但执行一些其他处理(在同一迭代中)而不等待该输入,则解决方案是将pthread_join()调用移过在收到用户输入之前可以完成的所有工作:

while (1) {
pthread_create(&thread_id, NULL, threadUserInput, NULL);
// do work that does not require the user input ...
pthread_join(thread_id, NULL);
// do work that _does_ require the user input (if any) ...
}

或者,也许您正在寻找更解耦的东西,循环会根据需要进行尽可能多的迭代,直到输入可用。 在这种情况下,您应该在循环外部启动 I/O 线程并保持其运行,读取一个又一个输入。 当有输入可供主线程使用时,让它提供某种信号。 示意性地,这可能看起来像这样:

pthread_create(&thread_id, NULL, threadAllUserInput, NULL);
while (1) {
// ... some work ...
if (get_input_if_available(/* arguments */)) {
// handle user input ...
}
// ... more work ...
}
force_input_thread_to_stop();
pthread_join(thread_id, NULL);

我省略了如何实施get_input_if_available()force_input_thread_to_stop()的所有细节。 有多种选择,其中一些比其他选择更适合您的特定需求。

最新更新