【发布时间】:2018-05-14 03:59:21
【问题描述】:
问题:创建一个接受用户输入但几秒钟后超时的程序(假设现在是 2 秒)。
方法:我创建了两个线程,一个等待用户输入(inputThread 和 tid[0]),另一个休眠 2 秒(sleepThread 和 tid[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;
}
截至目前,该程序按预期运行。
但我的朋友说它不能保证工作,因为它取决于线程的调度方式。他试图向我解释同样的事情,但我无法理解。他还说pthread_cancel只是一个取消线程的请求,它可能不会成功。
所以有人可以指出潜在的错误和避免相同的最佳做法。为保证程序正常工作而进行的任何更改也值得赞赏。
【问题讨论】:
标签: c multithreading pthreads