• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Help needed with the OS threads problem in C++

adlep

Diamond Member
Consider the following code C++ code..
int y =3; x = 0;
foo()
{
y=y+1;
x=y;
}

bar()
{
y=y*2;
}

main()
{
Thread t1= createThread(foo);
Thread t2= create Thread(bar);
WaitForAllDone();
cout << x << y << endl;
}
1. My question is what is the maximum number of threads that are ever alive in this program, the teacher didnt really explained anything, and I am still confused on how should I interpert such a code..?
2. What are all possible outputs for the program?
I think this means that it can be diffrient depending which operation thread will get executed first, but I am not sure...Help?
Man this Operating System class I am taking is tougher that I have expected....🙁
 
Well, I haven't had an OS class in over 10 years, but I think I can still help. 🙂

In answer to your first question, I'd say either 2 or 3 (one for "foo", one for "bar", and then one more if you're counting "main")

The second question isn't too hard to figure out. Basically, it looks like you're creating a "race condition" between two threads. Even though you're starting "foo" first, there is no guarantee it will finish before you start "bar". Remember, once you start a thread, it is COMPLETELY INDEPENDENT of your main program and other threads (I'm assuming your "create" statement both cretes and starts the thread).

All you have to do is look at the statements involved in "foo" and "bar". You have a total of 3 statements: "y=y+1", "x=y", and "y=y*2". Now how many ways can you write down those statements? The only thing you can be guaranteed is that "y=y+1" will execute before x=y as they are both within "foo".

If you run the program, I'm sure you'll notice you get different answers each time you run the program. Normally, you'd expect the sequence of operations to be something like this:

y=y+1 (foo)
x=y (foo)
y=y*2 (bar)

Unfortunately for you, both foo and bar are threads and can therefore be interrupted byt he CPU ay *ANY* time. This sequence is also equally likely as the one above:

y=y+1 (foo)
y=y*2 (bar)
x=y (foo)

Actually, to get the EXACT answer your second question you can't look at the C code, you have to look at the generated assembly code and realize that each thread can be interrupted at ANY single assembly instruction.

I hope all this rambling helps.


Dave
 
Back
Top