#include <windows.h>
#include <iostream>
#include <string>
#include <conio.h>
namespace jsw
{
namespace threading {
class auto_event {
public:
auto_event(): _event(CreateEvent(0, false, false, 0)) {}
BOOL wait(DWORD timeout = 1) const
{
return WaitForSingleObject(_event, timeout) == WAIT_OBJECT_0;
}
BOOL set() { return SetEvent(_event); }
private:
HANDLE _event;
};
class thread {
public:
static thread start(
LPTHREAD_START_ROUTINE fn, LPVOID args = 0,
DWORD state = 0, DWORD timeout = 1000)
{
return thread(CreateThread(0, 0, fn, args, state, 0), timeout);
}
static void sleep(DWORD milliseconds) { Sleep(milliseconds); }
static void exit(DWORD exitCode) { ExitThread(exitCode); }
public:
thread(HANDLE thread, DWORD timeout): _thread(thread), _timeout(timeout) {}
~thread() { CloseHandle(_thread); }
DWORD exit_code() const
{
DWORD exitCode = NO_ERROR;
GetExitCodeThread(_thread, &exitCode);
return exitCode;
}
HANDLE handle() const { return _thread; }
BOOL is_alive() const { return exit_code() == STILL_ACTIVE; }
DWORD join() { return WaitForSingleObject(_thread, _timeout); }
DWORD suspend() { return SuspendThread(_thread); }
DWORD resume() { return ResumeThread(_thread); }
BOOL abort(DWORD exitCode) { return TerminateThread(_thread, exitCode); }
private:
HANDLE _thread;
DWORD _timeout;
};
}
}
using namespace std;
DWORD WINAPI get_password(LPVOID args)
{
using namespace jsw::threading;
string *s = (string*)((LPVOID*)args)[0];
auto_event *e = (auto_event*)((LPVOID*)args)[1];
*s=getch();
e->set();
return NO_ERROR;
}
void time()
{
//...I'll get it
}
int main()
{
using namespace jsw::threading;
string password;
auto_event e;
LPVOID args[2] = {&password, &e};
thread worker = thread::start(get_password, args);
cout<<"time of game --> ";time();cout<<endl;
cout<<"Press one to go home"<<endl;
cout<<"Press two to drive your car"<<endl;
cout<<"Press three to visit near city"<<endl;
if (e.wait(1000))
{
if(password=="1") cout<<"House"<<endl;
else if(password=="2") cout<<"Car"<<endl;
else if(password=="3") cout<<"City"<<endl;
else cout<<"wrong option"<<endl;
}
else system("cls"); main();
return 0;
}
When the second on the clock changes and I select an option in the menu, I have to click the button several times because the first time the program does not load it. When starting the program, it loads correctly, but after a second, when the program uses else, I have to click the button several times.
(I need this procedure to change time with passing seconds in the program)
looking for a time limited cin I just found this code "namespace jsw" and "DWORD WINAPI". It works, because when the time is up, the program redisplays the menu with the changed time, but when retrieving a key there is a problem.