Bloomberg LP Interview Question
Software Engineer / DevelopersWhether the child process contains two threads depends the place where the two threads in the parent are created. If they are created after the creation of the child process, the child process will also have two threads. If we want to make threads safe, we should not protect the global variables in the same process. Is it right?
1. When a child process is created using fork, the stack of the calling thread is copied . Other threads is not copied to the child process.
2. For deadlock to occur, cycle is needed. From the Q, it appears that child process acquired the lock on resource(for example, file) of parent process. But it doesn't mention that parent process also acquire on resource of child process.... So, Q not clear..
3. Fork() is not thread safe. There can be side effect if other thread can create side-effect(for example, corruption of global variables, mutex etc).
1.
fork()
duplicates the current process.
exec()
tells a thread to executes another executable.
2. A deadlock can happen if you have the following:
a. Mutual exclusion, which means a resource that only one thread can use a time.
b. Hold & wait - hold a resource while you wait for another.
c. Non-Preemtion - you can't take the lock from another thread.
d. circular waiting - for processes (threads) p1...p_n, p_i is waiting for a resource held by p_(i-1).
So the question should be more clear.
3. If you have 2
fork()
, you'll have 4 threads (unless you exec() after the first
fork()
).
4. The question should be made clearer. In general, if after
fork()
you have, let's say,
printf(<whatever>)
, you can't predict the outcome. You need to use synchronization mechanisms.
The child process is created with a single thread -- the one that called
- Hitesh June 21, 2011fork(). The entire virtual address space of the parent is replicated in
the child, including the states of mutexes, condition variables, and other
pthreads objects; the use of pthread_atfork(3) may be helpful for dealing
with problems that this can cause.