我的目标很简单,打印每个超时值(例如2秒)“找不到输入”,直到用户使用cin命令设置输入为止。
我正在使用Linux通过以下命令进行编译:g ++ signaltest.cpp -lpthread
我需要使用pthread_cond_signal和pthread_cond_timedwait(不要对线程使用c ++ 11 API!),并且不使用sleep()。
这是我的代码:
#include <sys/time.h>
#include <unistd.h>
#include <iostream> // std::cout
#include <thread> // std::thread
#include <chrono> // std::chrono::seconds
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable, std::cv_status
const size_t NUMTHREADS = 1;
pthread_mutex_t mutex;/* = PTHREAD_MUTEX_INITIALIZER;*/
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutexattr_t Attr;
int value;
bool done = false;
void* read_value( void* id )
{
const int myid = (long)id; // force the pointer to be a 64bit integer
std::cin >> value;
done = true;
printf( "[thread %d] done is now %d. Signalling cond.\n", myid, done );
pthread_cond_signal( &cond );
}
int main ()
{
struct timeval now;
struct timespec timeout;
/* get current time */
gettimeofday(&now, NULL);
/* prepare timeout value */
timeout.tv_sec = 2;
timeout.tv_nsec = 0;
pthread_mutexattr_init(&Attr);
pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &Attr);
std::cout << "Please, enter an integer:\n";
pthread_t threads[NUMTHREADS];
int t = 0;
pthread_create( &threads[t], NULL, read_value, (void*)(long)t );
pthread_mutex_lock( &mutex );
int rt = 0;
while( !done )
{
rt = pthread_cond_timedwait( & cond, & mutex, &timeout );
std::cout << "no input found" << std::endl;
}
pthread_mutex_unlock( & mutex );
std::cout << "You entered: " << value << '\n';
return 0;
}
我希望每2秒钟打印一次“找不到输入”。
我实际上看到的是“没找到任何输入”被不断打印。
据我了解,在while循环中,命令“ pthread_cond_timedwait”应阻塞,直到发出信号(在用户输入之后)或超时为止。但不会发生。