【发布时间】:2021-08-05 15:30:05
【问题描述】:
我什至不确定线程是否是我想要完成的工作的一种方式,但我的直觉告诉我。
我在 while 循环中逐个字符地实现一个简单的输入。如果字符输入之间的时间大于 2 秒,则应该发生超时。超时目前是main函数中的一个简单的printf。
这是我的代码:
typedef struct {
clock_t startTime;
} timerStruct;
void *TimerThread(void *arg) {
timerStruct timerThreadArgument = *((timerStruct *) arg);
clock_t differenceTime;
while(1) {
differenceTime = clock() - timerThreadArgument.startTime;
int millis = differenceTime * 1000 / CLOCKS_PER_SEC;
if (millis >= TIMEOUT_TIME) {
return (void *) 2;
}
}
}
int main() {
pthread_t timerThreadId;
void *threadReturn;
char inputChar;
printf("Input characters one by one or paste the string:\n");
while (1) {
timerStruct *timerThreadArgument = malloc(sizeof(*timerThreadArgument));
timerThreadArgument->startTime = clock();
pthread_create(&timerThreadId, NULL, TimerThread, timerThreadArgument);
pthread_join(timerThreadId, &threadReturn);
if ((int) threadReturn == 2) {
printf("Timeout!\n");
}
scanf(" %c", &inputChar);
}
}
问题是,由于我使用的是 pthread_join 函数,它会阻止主线程执行和请求输入。我知道为什么会这样。如果我不使用 pthread_join 函数,我将无法从线程返回数据,这很重要,因为如果发生超时,我希望打破 while 循环。
如果有人对我如何解决这个问题有任何想法,请分享。 提前感谢您的宝贵时间。
【问题讨论】:
-
线程对此没有帮助。线程的合理使用只与计算绑定程序有关,而不是 I/O,尤其是不是 I/O 超时。
-
您应该在标准输入上使用
poll()并设置超时时间。
标签: c multithreading timer pthreads