Microsoft Interview Question
SDE-2sCountry: India
Interview Type: In-Person
Simple implementation would be like this.
#include System;
#include System.Threading;
#include System.Timers;
public class ThreadSafeTimer
{
private Object thisLock = new Object();
public static void Main()
{
public static Timer t = new Timer();
StartTimer(t);
StopTimer(t);
ResetTimer(t);
}
public static void StartTimer(Timer t)
{
lock(thisLock)
{
if(!t.Enabled)
{
t.Start();
}
}
}
public static void StopTimer(Timer t)
{
lock(thislock)
{
if(t.Enabled)
{
t.Stop();
}
}
}
public static void ResetTimer(Timer t)
{
lock(thisLock)
{
if(!t.Enabled)
{
t.Reset();
}
}
}
}
class Timer{
public:
Timer():_start(0),_stop(0)
{
}
void start()
{
std::lock_guard<std::mutex> g(_mutex);
time(&_start);
}
double stop()
{
std::lock_guard<std::mutex> g(_mutex);
time(&_stop);
double res = difftime(_stop,_start);
std::cout << "Elapsed: " << res << std::endl;
return res;
}
void reset()
{
std::lock_guard<std::mutex> g(_mutex);
_start=0;
_stop=0;
}
private:
std::mutex _mutex;
time_t _start;
time_t _stop;
};
int main(int argc, const char * argv[])
{
Timer timer;
std::vector<std::thread> workers;
for (int i = 0; i < 15; i++) {
workers.push_back(std::thread([&]()
{
if ( i%2 )
timer.start();
else if (!( i%2 ) )
timer.stop();
if ( i%3 )
timer.reset();
}));
workers[workers.size()-1].join();
}
timer.start();
this_thread::sleep_for(std::chrono::seconds(5));
timer.stop();
std::cout << "Hello, World!\n";
return 0;
}
- Anonymous March 22, 2017