rhl*_*lee 3 c pthreads getchar
我有一个可以进行大量处理的小程序。您可以通过按 Enter 键来打印进度。
我实现这一点的方法是在主线程中完成处理,同时我有一个 pthread 不断在 getchar() 上循环以等待输入键。
问题是当我完成处理时。发生这种情况时,主线程完成,但仍然等待按下 Enter 键,因为 getchar() 正在阻塞。
如何“取消”getchar()?
我能想到的最便携的解决方案是:
pipe()构造两个 FD,一个为读取器,另一个为写入器。让读者了解你的read()循环;将作者交给任何需要终止读者的人。select()来等待标准输入和读取器管道的可读性。现在,您所要做的就是关闭管道的另一端,这会将读取器线程唤醒select(),然后它应该终止。
传统方法涉及使用信号,但是这种基于管道的解决方案允许您检查 stdin 上的输入以及检查是否应该使用相同的轮询机制终止。
请注意,混合getchar()和select()不会起作用,因为它将在幕后getchar()有效使用,并且即使有可用数据,执行的缓冲也可能导致阻塞。代替使用。这是我用来测试这种方法的示例程序。fread()fread()select()read()
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/select.h>
void * entry_point(void * p) {
int readpipe = *(int *)p;
fd_set rfds;
char c;
for (;;) {
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
FD_SET(readpipe, &rfds);
while (select(readpipe + 1, &rfds, NULL, NULL, NULL) == 0);
if (FD_ISSET(readpipe, &rfds)) {
close(readpipe);
break;
}
if (FD_ISSET(STDIN_FILENO, &rfds)) {
if (read(STDIN_FILENO, &c, sizeof(c)) > 0) {
printf("Read: %d\n", c);
}
}
}
printf("Thread terminating\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int r;
int pipes[2];
pipe(pipes);
if (r = pthread_create(&thread, NULL, entry_point, &pipes[0])) {
printf("Error: %d\n", r);
return 1;
}
sleep(5);
printf("Closing pipe and joining thread.\n");
close(pipes[1]);
pthread_join(thread, NULL);
pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)
运行示例:
$ time ./test
1
Read: 49
Read: 10
2
Read: 50
Read: 10
3
Read: 51
Read: 10
4
Read: 52
Read: 10
5
Read: 53
Read: 10
Closing pipe and joining thread.
Thread terminating
real 0m5.004s
user 0m0.004s
sys 0m0.000s
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5120 次 |
| 最近记录: |