gpt4 book ai didi

c - 处理两个线程,一个休眠,一个等待输入

转载 作者:行者123 更新时间:2023-12-01 12:13:02 25 4
gpt4 key购买 nike

问题:创建一个接受用户输入但在几秒后超时(假设现在是 2 秒)的程序。

方法: 我创建了两个线程,一个用于等待用户输入(inputThreadtid[0]),另一个用于休眠2 秒(sleepThreadtid[1])。我从另一个线程的例程中取消一个线程,如下所示:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_t tid[2];

void* inputThread()
{
int n;
printf("Enter number:");

// wait for input; if input is given then go ahead and cancel the sleeper thread.
scanf("%d",&n);

// cancel the sleeper thread
pthread_cancel(tid[1]);

printf("Got value:%d\n",n);
}

void* sleepThread()
{
// sleep for 2 seconds and cancel the input thread.
sleep(2);

// cancel the input thread
pthread_cancel(tid[0]);

printf("\nNo value entered!\n");
}

int main(int argc, char const *argv[])
{
int r1,r2,r3,r4;

// input taking thread
r1 = pthread_create(&tid[0],NULL,inputThread,NULL);

// sleeping thread
r2 = pthread_create(&tid[1],NULL,sleepThread,NULL);

r3 = pthread_join(tid[0],NULL);
r4 = pthread_join(tid[1],NULL);

return 0;
}

截至目前,该程序按预期运行。

但我的 friend 说它不能保证工作,因为它取决于线程的调度方式。他试图向我解释同样的事情,但我听不懂。他还说 pthread_cancel 只是一个取消线程的请求,它可能不会成功。

所以有人可以指出潜在的错误和避免相同错误的最佳实践。为保证程序正常运行而进行的任何更改也表示赞赏。

最佳答案

关于 pthread_cancel 是取消线程的请求并且可能不会总是成功的部分,您的 friend 是正确的。

关于日程安排的部分,您需要提供他的论据。

为了解决您的问题,您可以放弃一起使用线程(除非这是您的任务的要求)并使用 selectread .

这将使解决方案不可移植(仅符合 POSIX),但 pthreads 无论如何也是不可移植的。

select 允许您等待文件描述符(在本例中为 0)以等待数据可供读取。它还允许您设置超时。

fd_set set;
FD_ZERO(&set);
FD_SET(0, &set);

struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;

int ret = select(1, &set, NULL, NULL, &timeout);

if (ret == 1) {
char buffer[20];
int n;
read(0, buffer, 20);
sscanf(buffer, "%d", &n);
printf("Got value:%d\n",n);
} else {
printf("Time out\n");
}

关于c - 处理两个线程,一个休眠,一个等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50322919/

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