英文:
'scanf()' function does not work in C while multithreading
问题
以下是您要翻译的内容:
"Where is the code I have used in a thread.
void *input() {
while (1) {
if (image_should_take_input) {
scanf("%s \n", IE_image_command);
image_should_take_input = false;
}
}
}
And this code is in the other thread.
This code is in a while loop too.
....more code...
if (image_should_show_input_text) {
printf("-> ");
image_should_show_input_text = false;
image_should_take_input = true;
}
...more code...
and here is the code I have written in main() function:
int main() {
pthread_t input_thread;
pthread_t output_thread;
if (pthread_create(&input_thread, NULL, &input, NULL)) return 1;
if (pthread_create(&output_thread, NULL, &output, NULL)) return 1;
if (pthread_join(input_thread, NULL)) return 1;
if (pthread_join(output_thread, NULL)) return 1;
return 0;
}
The problem is if I run it the '->' prints but a cannot give any input that means scanf() does not function run. Why?"
英文:
Where is the code I have used in a thread.
void *input() {
while (1) {
if (image_should_take_input) {
scanf("%s \n", IE_image_command);
image_should_take_input = false;
}
}
}
And this code is in the other thread.
This code is in a while loop too.
....more code...
if (image_should_show_input_text) {
printf("-> ");
image_should_show_input_text = false;
image_should_take_input = true;
}
...more code...
and here is the code I have written in main() function:
int main() {
pthread_t input_thread;
pthread_t output_thread;
if (pthread_create(&input_thread, NULL, &input, NULL)) return 1;
if (pthread_create(&output_thread, NULL, &output, NULL)) return 1;
if (pthread_join(input_thread, NULL)) return 1;
if (pthread_join(output_thread, NULL)) return 1;
return 0;
}
The problem is if I run it the '->' prints but a cannot give any input that means scanf() does not function run. Why?
答案1
得分: 2
你的代码不起作用,因为你在不使用任何同步机制的情况下从不同的线程中读取和/或修改了同一个变量image_should_take_input
。
声明这个变量为volatile
是不足以提供适当的同步的。
input
线程有一个一直以最大速度运行的忙等待循环,这是非常不好的做法。
如果这个程序的目的是学习线程,你需要学习锁、互斥锁和信号量,否则,你可能根本不应该使用线程。
英文:
Your code does not work because you read and/or modify the same variable image_should_take_input
from different threads without any synchronisation mechanism.
Declaring this variable volatile
is not enough to provide proper synchronisation.
The input
thread has a busy loop that runs at full speed all the time, which is very bad practice.
If the purpose of this program is to learn about threads, you need to study locks, mutex and semaphores, otherwise, you should probably not use threads at all.
答案2
得分: -1
答案是,我甚至不太了解 'volatile' 关键字。在了解它之后,原来它就是解决方案。
而且,当循环实际可以运行时,我可能还需要设置一个定时器。
感谢 @chqrlie 指出这一点。
英文:
The answer is that I didn't even know much about 'volatile' keyword. After knowing about it, it turns out that it was the solution.
And I also might have to set a timer when the loop actually can run.
Thanks to @chqrlie to point it out.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论