Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Recall that the compiler is unaware that an ordinary C program is multithreaded, and as a consequence, it may make optimizations that can interfere with

image text in transcribed

Recall that the compiler is unaware that an ordinary C program is multithreaded, and as a consequence, it may make optimizations that can interfere with busy-waiting. (Note that compiler optimizations should not affect mutexes, condition variables, or semaphores.) An alternative to completely turning off compiler optimizations is to identify some shared variables with the C keyword volatlle. This tells the compiler that these variables may be updated by mutiple threads and, as a consequence, it shouldn't apply optimizations to statements involving them. As an example, recall our busy-wait solution to the race condition when multiple threads attempt to add a private variable into a shared variable: /x and flag are shared, y is private /x and flag are infifilized to 0 by main thread / y= Compute(my_rank): while (flag != my_rank): x=x+y: flagt+: It's impossible to tell by looking at this code that the order of the whlle statement and the x =x+y statement is important; if this code were single-threaded, the order of these two statements wouldn't affect the outcome of the code. But if the compiler determined that it could improve register usage by interchanging the order of these two statements, the resulting code would be erroneous. If, instead of defining int flag: int x : we define Int volat1le flag: int volatile x : then the compiler will know that both x and flag can be updated by other threads, so it shouldn't try reordering the statements. With the gcc compiler, the default behavior is no optimization. You can make certain of this by adding the option 00 to the command line. Try running the calculation program that uses busy-waiting (pth_pi_busy.c) without optimization. How does the result of the multithreaded calculation compare to the single-threaded calculation? Now try running it with optimization; if you're using gcc, replace the 00 option with 02. If you found an error, how many threads did you use? Which variables should be made volatile in the calculation? Change these variables so that they're volatile and rerun the program with and without optimization. How do the results compare to the single-threaded program

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions