Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Blocks and Thread Priority

Tags:

c++

When I put code in blocks, like so:

    {
      f1();
      f2();
    }

Does it GUARANTEE that those two functions will be called after one another by the CPU regardless of what other processes are running?

The reason I ask is because f1, in my case, does something with the OS, then f2 relies on the the OS being in the same state in order to work properly.

If not, (which I really don't think it does), is there any C++ construct that will help me do something like this?

Also, I'll give some background information about what's being done in my real code:

f1() is actually a function that spawns a top-level window on a win32 system. f2() is a function that searches for the top-most level window (that is not the taskbar). So, my concern is that I could run into an issue wherein other top-level windows may be created in the time between when f1 finishes and f2 has not yet been executed, in which case f2 will find the wrong window.

like image 742
kwikness Avatar asked Sep 17 '26 08:09

kwikness


2 Answers

Does it GUARANTEE that those two functions will be called after one another by the CPU regardless of what other processes are running?

Yes. If those functions spawn threads or whatever, they may run in different orders. But the actual code for those functions will be executed in order.

If you're talking about access to anything outside of your process, that's a different matter. C and C++, as languages, have no concept of concurrency and such (outside of a few language features like volatile). Everything within a program is sequential, but the world outside of your program is unknown and unknowable (without a library that provides such hooks).

If the library in question does not provide a way to prevent another process from touching some global state that your code touched, then you have no way to be sure that the state will remain set as you set it.

like image 111
Nicol Bolas Avatar answered Sep 19 '26 01:09

Nicol Bolas


f2 could run not directly after f1, and f2 should therefore not rely on the system being in the state that f1 left it in. In fact, neither should be playing with state on a multi-threaded system unless you have the proper locks in place.

However, it is guaranteed that f1 will have returned before f2 is called.

like image 36
Lightness Races in Orbit Avatar answered Sep 19 '26 01:09

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!