Đối với dạng toán này thì chỉ có cách dùng thread mới giải quyết vấn đề. Bạn tham khảo nhé
Code:
#include <windows.h>
#include <iostream>
using namespace std;
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 = 5000)
{
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;
};
}
}
#include <iostream>
#include <string>
int n;
DWORD WINAPI get_n(LPVOID args)
{
using namespace jsw::threading;
n = (int)((LPVOID*)args)[0];
auto_event *e = (auto_event*)((LPVOID*)args)[1];
cin>>n;
e->set();
return NO_ERROR;
}
int main()
{
using namespace jsw::threading;
auto_event e;
LPVOID args[2] = {&n, &e};
thread worker = thread::start(get_n, args);
if (e.wait(5000))
cout<<'\n'<< n <<"";
else {
worker.abort(NO_ERROR);
cout<< "time out";
}
system("pause");
}