gpt4 book ai didi

c - 使用 C 中的线程获取用户输入而不阻塞 while 循环

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:44 24 4
gpt4 key购买 nike

我想在 while 循环中从用户那里获取一个值,即变量的设定值,而不阻止执行其他任务。我正在尝试使用 pthreads,但我的试用失败了。即使我正在使用 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: %d\n", refAngle);

return NULL;
}

如有任何帮助,我们将不胜感激,在此先致谢。

最佳答案

Even though I am utilizing pthread, the program is blocked by the scanf function.

嗯,是的。创建的线程阻塞在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() 的所有细节。有多种选择,其中一些比其他更适合您的特定需求。

关于c - 使用 C 中的线程获取用户输入而不阻塞 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55640416/

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