Microsoft Interview Question for SDE-2s


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 0 vote

from threading import Thread, Lock
import time

class TimeException(Exception):
	pass

class Timer:
	def __init__(t, init):
		t.init = init
		t.lock = Lock()
		t.kill = False

	def timer_thread(t):
		t.current = t.init
		while True:
			try:
				t.lock.acquire()

				if t.current<= 0: break
				if t.kill: break
				
				t.current -= 1
				print t.current
			finally:
				t.lock.release()			
			time.sleep(1)
	
	def reset(t):
		try:
			t.lock.acquire()
			t.current = t.init
		finally:
			t.lock.release()
	
	def stop(t):
		try:
			t.lock.acquire()
			t.kill = True
		finally:
			t.lock.release()

	def time(t):
		try:
			t.lock.acquire()
			return t.current
		finally:
			t.lock.release()

	def start(t):
		Thread(target=t.timer_thread).start()

t = Timer(5)
t.start()
time.sleep(2)
t.reset()
time.sleep(2)
t.stop()

- Anonymous March 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
			}
		}
	}
}

- sonesh March 30, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- drolmal April 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <chrono>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>

class ThreadSafeTimer {
private:
    std::mutex mtx;
    std::chrono::steady_clock::time_point start_time;
    std::chrono::duration<double> elapsed{0};
    bool running = false;

public:
    void Start() {
        std::lock_guard<std::mutex> lock(mtx);
        if (!running) {
            start_time = std::chrono::steady_clock::now();
            running = true;
        }
    }

    void Stop() {
        std::lock_guard<std::mutex> lock(mtx);
        if (running) {
            auto end_time = std::chrono::steady_clock::now();
            elapsed += end_time - start_time;
            running = false;
        }
    }

    void Reset() {
        std::lock_guard<std::mutex> lock(mtx);
        running = false;
        elapsed = std::chrono::duration<double>::zero();
    }

    double Elapsed() {
        std::lock_guard<std::mutex> lock(mtx);
        if (running) {
            auto current_time = std::chrono::steady_clock::now();
            return std::chrono::duration_cast<std::chrono::duration<double>>(elapsed + (current_time - start_time)).count();
        }
        return elapsed.count();
    }
};

int main() {
    ThreadSafeTimer timer;

    timer.Start();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    timer.Stop();

    std::cout << "Elapsed time: " << timer.Elapsed() << " seconds" << std::endl;

    timer.Reset();
    timer.Start();
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Elapsed time after reset and 2 seconds: " << timer.Elapsed() << " seconds" << std::endl;

    return 0;
}

Output:

Elapsed time: 1.00007 seconds
Elapsed time after reset and 2 seconds: 2.00007 seconds

- igvedmak March 28, 2024 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More