Microsoft Interview Question
SDE1sCountry: United States
Interview Type: In-Person
private static volatile YourObject instance;
public YourObject getInstance() {
YourObject r = instance;
if(r == null) {
synchronized(lock) { // while we were waiting for the lock, another
r = instance; // thread may have instantiated instance
if(r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
numerous ways
while( x == 0 )
{
lock() /* more than one thread will end up waiting here first time */
if( x == 0 ) /* one of the thread grabs a lock and first one to do will find x is 0 */
x=1; /* only first thread will update it, others will simply unlock and exit loop */
unlock()
}
Other than that, there are instruction like compare and swap which are atomic
/* compare x with 0, if x is 0 then set x as 1- do this atomically */
/* processor has instruction called cmpxchg */
__sync_val_compare_and_swap( &x, 0, 1 ); /* compare value of x with 0, if same only then update it to 1 */
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
int x = 0;
std::once_flag flg;
void setX(const int n) {
x = n;
std::cout << "setX: " << n << std::endl;
}
void wait_and_set(const int id) {
std::this_thread::sleep_for(std::chrono::microseconds(100));
std::call_once(flg, setX, id);
}
int main() {
std::vector<std::thread> tLst;
for (int i = 1; i < 10; ++i) {
tLst.push_back(std::thread(wait_and_set, i));
}
for (auto& t : tLst) t.join();
std::cout << "The final value of x is " << x << std::endl;
std::cin.get();
std::cout << "Press Enter to continue ..." << std::endl;
return 0;
}
{{
- Mohamed May 17, 2013if(x==0){
lock(x);
if(x==0){
x=newTime();
}
unlock(x);
}
}}