Exercise 2

Exercise 2

von Ehsan Sasanianno -
Anzahl Antworten: 3

Hi, 

I hope you are well. 

I have a problem running the code. When I run the code with the command "./configure.sh && make && ./bogus 1 9" - which compiles the code with no optimization and runs it in a single-threaded mode, I see a wrong output. According to the code, I assume a single thread runs 10 to the power of 9 increment operation which should result in "1000000000". The output result is correct but it takes zero seconds for the program to run the code! This behavior is strange. Even by increasing 9 to 19, it still runs the code in zero seconds with the correct output. The code is utilized on a MacBook Pro with an M2 processor with Apple Clang version 15.0.0 GCC.

I would appreciate any help here.

Bests Regards,

Ehsan

Als Antwort auf Ehsan Sasanianno

Re: Exercise 2

von Jonas Reichhardt -
Hey Ehsan,

The program only prints three decimal places.
To change that, substitute the numbers in the %.3f part of line 175 (of the unmodified program) then you should see an output.

Good luck,
Jonas
Als Antwort auf Jonas Reichhardt

Re: Exercise 2

von Ehsan Sasanianno -
Thanks for your prompt response! Yes, indeed changing that fixed the issue.
I have a follow-up question. When I run the optimized version of bogus with two threads, I still see the correct result. However, I am expecting a race condition there. Please note that running the un-optimized version of the same code 'Error'! Also, when I add the volatile keyword to the vars (for part 3), a race condition occurs for both optimized and un-optimized versions. As I am not an expert in C compiler, does the compiler fix the race condition in the optimized version?

Thanks again!
Ehsan
Als Antwort auf Ehsan Sasanianno

Re: Exercise 2

von Alois Zoitl -

Unfortunately the compiler can not fix any race conditions for you. When turning on optimizations the execution time of your code part changes. This can result that the race condition is less or more visible. Depending on your CPU and other programs you are running.  Seeing correct runs are in your case happening on accident.