πŸŽ“ BookMCQ
← Back to 5. Process Synchronization

πŸ“ Functional Programming Languages Alternative Approache in Process Synchronization (36 MCQs)

Functional Programming and Reduced Shared-State Dependencies

Functional programming provides an alternative approach to concurrency by emphasising pure functions, immutable data, and expressions that produce results without modifying shared state. In operating system and parallel application contexts, these properties reduce many synchronization requirements because independent operations can safely read the same immutable values. Execution systems can distribute functional computations across threads or processor cores with fewer shared-memory conflicts.

Why Mutable Shared Variables Complicate Concurrent Execution

Imperative concurrent programs often modify shared variables, creating race conditions when multiple threads access them without coordination. Functional programming reduces this problem by discouraging shared mutable state and favouring new values instead of in-place modification. This approach makes independent computations easier to execute concurrently, although external side effects and mutable references still require appropriate coordination.

Pure Functions, Immutable Data, and Parallel Evaluation

A pure function produces the same result for the same input without changing external state. Immutable data cannot be modified after creation, allowing several execution threads to read it safely. Parallel evaluation frameworks distribute independent function calls or collection operations across available workers, while controlled mechanisms handle necessary input-output operations and mutable interactions.

Parallel Processing of an Immutable Data Collection

Suppose a program contains 10,000 immutable numerical values and must calculate their squares. Four worker threads process separate portions using the same pure function. Each computation produces independent results without modifying the original collection. The runtime can combine the resulting values after the tasks finish, reducing the need for locks around the input data.

Reduced Locking, Parallel Scalability, and Remaining Limitations

Functional programming can simplify parallel computation by reducing shared mutable state and the synchronization required to protect it. It is useful in data processing, scientific applications, and concurrent services. However, file access, network communication, mutable references, and other side effects still require coordination. Immutable data may also increase memory allocation and copying costs in some implementations.

Misconceptions About Functional Programming and Concurrency

'Functional programs never use mutable state' is incorrect because many languages permit controlled mutation. 'Pure functions require locks for every shared input' is incorrect because immutable input can be read concurrently. 'Functional programming eliminates all synchronization' is incorrect because external side effects and resource coordination still require controlled execution.

Exam Focus: Pure Functions and Lock-Free Parallel Computation

Distinguish pure functions, immutable values, and side effects, and explain why immutable shared data reduces race conditions. Trace independent functional operations across multiple worker threads. Questions may compare functional and imperative synchronization approaches, assess parallel data processing, and identify situations where external resource access or mutable state still requires coordination.

Key Terms of Functional Concurrency

  • Pure function - Produces results without external side effects.
  • Immutability - Prevents modification after value creation.
  • Side effect - Operation changing external program state.
  • Referential transparency - Expression replaceable by its result.
  • Parallel evaluation - Independent computations execute simultaneously.
  • Shared mutable state - Modifiable data accessed by threads.
12
Easy
12
Medium
12
Hard

πŸ“ All Functional Programming Languages Alternative Approache in Process Synchronization MCQs

Q1. Which description best characterizes the functional approach when several computations may run concurrently?

A.Programs are expressed as evaluations of functions and expressions, with little reliance on commands that mutate shared state. βœ…
B.Programs coordinate every expression through one global mutex.
C.Programs require each function to update a shared status variable.
D.Programs replace concurrent execution with a single permanent process.
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: Functional programs describe computation by evaluating expressions and composing functions. They reduce reliance on assignment commands and changing shared state, removing many common synchronization conflicts between concurrent tasks in parallel systems.

Q2. A data-processing service expresses each stage as a function whose result feeds the next stage. Why can this style simplify concurrent execution?

A.Every stage must execute on the same thread to preserve variable values.
B.The data dependencies identify required ordering, while independent stages need not coordinate through shared mutable variables. βœ…
C.Function composition automatically creates a lock for each stage.
D.The operating system must execute composed functions in source-code order.
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: Functional descriptions emphasize the values produced and the dependencies between expressions, rather than a sequence of mutations. Independent expressions can therefore run in different orders when dependencies permit, without changing the specified result.

Q3. A service defines f(x) = x + 3 and g(x) = 2x. If it evaluates g(f(4)) as a composed computation, what value is returned?

A.11
B.8
C.14 βœ…
D.10
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: First evaluate the inner function: f(4) = 4 + 3 = 7. Then apply the outer function: g(7) = 2 Γ— 7 = 14. Composition preserves this dependency order rather than permitting reversal of their order.

Q4. A student says a function is pure because it returns the same displayed answer each time, even though it increments a global call counter. Which part of the reasoning is flawed?

A.A pure function must always return a different value on each call.
B.Changing a local temporary variable is always a shared-state race.
C.A function is pure only when it is executed by the kernel.
D.The function changes external state, so identical displayed return values do not make it pure. βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: The flawed step is treating an unchanged return value as sufficient proof of purity. Incrementing a global counter is an observable side effect; a pure function must not modify external state.

Q5. A server parallelizes independent pure transformations. Its measured throughput is given as (workers, results per second): (1,100), (2,195), (4,380), (6,555), (8,715). What throughput is recorded with six workers?

A.555 results per second βœ…
B.380 results per second
C.600 results per second
D.715 results per second
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: Read the data pair whose worker count is six: (6,555). The recorded throughput is therefore 555 results per second; the question asks for the measured value, not an extrapolation or ideal linear speedup.

Q6. Two worker threads receive the same immutable request and independently calculate a checksum and a category. Why can the operating system schedule these calculations in either order safely?

A.The scheduler guarantees that the first worker always finishes before the second.
B.Each calculation depends only on its input and produces a result without modifying shared request data. βœ…
C.Immutable input automatically serializes the workers at the hardware level.
D.The workers share a counter whose updates are atomic by definition.
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: The computations read the same stable input and do not mutate it. Their results are independent, so scheduling order does not create a race on request data, although later side effects may still require coordination.

Q7. Which pair of properties most directly identifies a pure function?

A.The function uses recursion and always runs on one processor.
B.The function reads global variables but never writes them.
C.The same inputs produce the same outputs, and the function has no externally visible side effects. βœ…
D.The function returns a value and also updates a shared cache.
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: Purity combines deterministic behavior for a given input with the absence of external side effects. Reading mutable external state can also break purity because the result may depend on conditions outside the arguments.

Q8. A function calculates shipping cost using its argument for package weight but reads a mutable global fuel surcharge. Why is it not pure?

A.A pure function is not permitted to perform multiplication.
B.Global values are safe dependencies whenever a function only reads them.
C.A function becomes pure as soon as its result is stored in a local variable.
D.Its output depends on external mutable state that is not represented in the function arguments. βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: The global surcharge can change between calls without changing the explicit argument. The function therefore has a hidden dependency; passing the surcharge as an argument makes the calculation's inputs explicit.

Q9. A functional data pipeline applies a pure doubling function to the list [2, 4, 5]. What list should the mapping operation return?

A.[4, 8, 10] βœ…
B.[2, 4, 5]
C.[3, 5, 6]
D.[4, 6, 7]
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: Mapping the doubling function applies it independently to every element: 2 becomes 4, 4 becomes 8, and 5 becomes 10. The resulting list is [4, 8, 10], while the original input remains unchanged.

Q10. A developer claims that a calculation function is pure because it never changes its numeric result, but it writes a diagnostic line to a file on every call. What is the error?

A.Writing a file is pure whenever the function returns a number.
B.File output is an external side effect, so the function is not pure even when its returned number is stable. βœ…
C.Only file reads, not file writes, can affect program behavior.
D.The function is impure because pure functions cannot accept numeric arguments.
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: The flawed reasoning ignores the file write. File output changes external state and can be observed independently of the returned number, so the operation must be kept outside the pure calculation or modeled explicitly.

Q11. A pure function h is tested with the following data pairs (input, output): (1,4), (2,7), (3,10), (4,13), (5,16). What output corresponds to input 4?

A.10
B.12
C.13 βœ…
D.16
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: The supplied pair for input 4 is (4,13), so the output is 13. The consistent pattern also fits h(x) = 3x + 1, but the answer follows directly from the recorded mapping.

Q12. Let f(x) = x + 2 and g(x) = 3x, both pure. A developer evaluates g(f(4)) but mistakenly reverses the composition. Which pair gives the correct result and the mistaken reversed result?

A.14 for g(f(4)) and 18 for f(g(4))
B.18 for both expressions
C.12 for g(f(4)) and 16 for f(g(4))
D.18 for g(f(4)) and 14 for f(g(4)) βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: The correct order gives f(4) = 6, then g(6) = 18. Reversing the functions gives g(4) = 12, then f(12) = 14; composition order matters even for pure functions without altering their definitions.

Q13. What does immutability mean for a data value shared by several threads?

A.Once created, that value cannot be changed; an update produces a different value instead. βœ…
B.The value can be changed only by the thread that created it.
C.The value is automatically copied into a private address space for every read.
D.The value is locked permanently after its first access.
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: An immutable value remains unchanged after creation. Code that needs a modified result creates a new value or version, allowing concurrent readers to share the original without racing over updates to it.

Q14. A reporting service allows many workers to read the same immutable configuration object. Why can those reads normally proceed without a mutex protecting the object?

A.A mutex is unnecessary because read operations always execute atomically.
B.No worker can change the shared object, so concurrent reads cannot conflict with writes to that object. βœ…
C.The operating system converts every read into a private copy automatically.
D.Immutable objects cannot be stored in shared memory.
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: A read-read overlap is safe when the object cannot be mutated by any participant. Immutability removes the write side of the race, although other mutable resources accessed by the workers may still need protection.

Q15. A client holds the immutable list [A, B, C]. It needs a new list with D appended while preserving the original for another worker. Which result meets that requirement?

A.Append D directly to the shared original list.
B.Replace C with D in the original list and notify the other worker.
C.Create [A, B, C, D] as a new list and leave [A, B, C] unchanged. βœ…
D.Clear the original list before constructing [D, A, B, C].
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: The update must produce a new list containing A, B, C, and D while retaining the original value. This lets another worker continue reading the earlier version without observing a partial mutation.

Q16. A programmer passes a constant reference to a list into two workers and concludes that the list is immutable. Another alias can still modify the same list. What is wrong with the conclusion?

A.A constant reference forces every alias to become constant automatically.
B.The list is immutable only when both workers run on separate processors.
C.The second alias can modify the list only after the first worker exits.
D.A constant reference restricts mutation through that reference but does not guarantee that the underlying object is immutable through every alias. βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: The flawed step equates a read-only access path with deep immutability. Another alias may still mutate the underlying object, so safe sharing requires controlling all mutation paths or using a genuinely immutable value.

Q17. A team records the number of elements visible in its original immutable list after each derived version. The data are (version, original-list size): (0,5), (1,5), (2,5), (3,5), (4,5). What conclusion is supported?

A.Creating derived versions has not changed the original list's five-element value. βœ…
B.Each derived version must contain exactly five additional elements.
C.The original list is being modified and restored after every operation.
D.The versions cannot contain any elements because the size is constant.
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: Every recorded version still observes five elements in the original value. This is consistent with immutable updates creating separate versions rather than changing the shared original list in place across all versions.

Q18. Two workers start from the same immutable balance record. One produces a new record adding a deposit; the other produces a new record subtracting a fee. What does immutability guarantee, and what remains necessary?

A.The operating system automatically merges both new records into one correct balance.
B.Neither worker corrupts the shared starting record, but the application still needs a rule to combine or order both updates. βœ…
C.Both workers must use a mutex to read the unchanged starting record.
D.The second update always overwrites the first because immutable values cannot be copied.
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: Immutability prevents either worker from changing the common starting record, so their calculations do not race on it. A merge or ordering policy is still needed to incorporate both results correctly.

Q19. What is referential transparency in a functional program?

A.A variable can be reassigned whenever another thread requests it.
B.A function call must be repeated to refresh its stored result.
C.An expression can be replaced by its value without changing the program's observable behavior. βœ…
D.Every expression must execute exactly once and in source order.
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: Referential transparency allows an expression to be substituted by its value in any valid context. This relies on the expression having no hidden state changes or dependencies that make the substitution observable.

Q20. A compiler wants to evaluate two independent expressions in parallel. How does referential transparency help it reason about this transformation?

A.It guarantees that every expression consumes equal CPU time.
B.It removes data dependencies between expressions that use one another's results.
C.It requires the compiler to execute all expressions in reverse order.
D.Pure expressions can be substituted by their values, so changing their evaluation order does not introduce hidden state changes. βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: Referentially transparent expressions have no hidden side effects, so their evaluation can be moved or repeated when data dependencies allow. The property does not remove genuine dependencies between one expression and another.

Q21. A worker evaluates the pure function p(x) = 2x + 1 for x = 8. What value may another worker obtain by evaluating the same function with the same input?

A.17 βœ…
B.16
C.18
D.9
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: Substitute the input into the function: p(8) = 2 Γ— 8 + 1 = 17. Because the function is pure and receives the same input, another worker must obtain the same result regardless of scheduling order.

Q22. A student replaces a call to calculateTotal(50) with the literal 50 in an expression. The function also increments a global audit counter. Why may this replacement change program behavior?

A.The literal has a different numeric type from every function result.
B.The original call increments external state, while the literal substitution does not perform that side effect. βœ…
C.A function call can never be replaced by a literal in any language.
D.The audit counter makes the returned total automatically equal to zero.
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: The replacement removes the function's global counter update. Although the numeric result may match, the program's observable state differs, so the function call is not referentially transparent and cannot be freely substituted.

Q23. A benchmark reports speedup for independent pure tasks as (workers, speedup): (1,1.0), (2,1.9), (4,3.6), (6,5.1), (8,6.4). Which statement best describes the measured result at six workers?

A.The measured speedup is six times and therefore perfectly linear.
B.The measured speedup is 3.6 times, because four workers are nearest to six.
C.The measured speedup is 5.1 times, which is below ideal linear speedup of six times. βœ…
D.The measured speedup is 8 times, because each worker contributes one unit.
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: The table gives a speedup of 5.1 at six workers. Ideal linear scaling would be 6.0, so the measurement shows useful parallel scaling with some overhead or other limits.

Q24. A program runs pure calculations concurrently and then writes each result to a shared log in a required chronological order. Which design best respects both requirements?

A.Place one global lock around all calculations and logging to force serial execution.
B.Let each worker write immediately because pure calculations make file output pure.
C.Discard the required order because referential transparency applies to file operations.
D.Run the pure calculations independently, then route completed results through an ordered logging stage. βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: Pure calculations can proceed independently, but writing to one log is an external effect with an ordering requirement. Separating the ordered logging stage preserves concurrency without pretending the I/O is pure.

Q25. Which operation is an example of a side effect that a pure calculation should not perform directly?

A.Writing a record to a shared file βœ…
B.Adding two supplied integers
C.Selecting the larger of two supplied values
D.Returning a newly constructed list
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: Writing a shared file changes state outside the function and can be observed by other components. Arithmetic, comparison, and constructing a returned value can remain pure when they use only supplied inputs.

Q26. Why do practical functional programs still need a controlled way to perform input and output?

A.Input and output are automatically converted into pure arithmetic operations.
B.Programs must interact with external devices and services, so effects are isolated or explicitly represented rather than eliminated entirely. βœ…
C.Functional programs cannot communicate with users or external systems.
D.Every input operation must be protected by the same mutex as every output operation.
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: A useful program must read input, display results, and communicate with external services. Functional design controls where these effects occur so the core computations remain easier to reason about and test.

Q27. An online store calculates a discount and shipping estimate, then charges a card and records the purchase. Which design best separates pure computation from effects?

A.Charge the card inside the discount function so both operations share one return value.
B.Store the card result in a global variable read by every pure function.
C.Calculate the discount and estimate in pure functions, then perform charging and recording in an explicit effect-handling layer. βœ…
D.Avoid calculating the estimate until after the external charge has completed.
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: Discount and shipping calculations can depend only on explicit inputs and return predictable values. Charging a card and recording a purchase change external systems, so they belong in a controlled effect-handling layer.

Q28. A function named eligible(user) checks the current system time internally to decide whether a user qualifies. A student labels it pure because it does not write variables. What is the flaw?

A.The function is pure because reading a clock never affects a result.
B.The function is impure only if it uses recursion as well as a clock.
C.The function must return a new user object to become pure.
D.The function depends on external time, so its result can change for the same explicit user input. βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: The flawed step assumes that only writes are side effects. Reading the clock introduces a hidden external dependency, so the same user argument may produce different results at different times.

Q29. A functional application must load a file, transform its records, and display a summary. Which arrangement best preserves a testable pure core?

A.Keep file access and display at the program boundary, and pass loaded records into pure transformation functions. βœ…
B.Let every transformation function reopen the file and rewrite it after processing.
C.Make the transformation functions depend on the current screen contents.
D.Store all records in a global mutable list shared by every function.
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: Separating file access and display from transformations makes the core functions deterministic and easy to test with supplied records. The outer boundary handles the unavoidable interaction with the external world.

Q30. A web server filters requests with pure functions in parallel, then updates a shared database counter for each accepted request. Which statement is most accurate?

A.The database update is automatically safe because the filtering stage is pure.
B.Filtering can be parallelized without shared-state locks, but the database counter update still needs an atomic or transactional coordination mechanism. βœ…
C.The filtering stage needs a mutex, while database updates need no coordination.
D.The whole request pipeline is pure because every function returns a value.
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: Purity protects the independent filtering computations, not the mutable database counter. Concurrent updates to that counter can still be lost, so the storage operation needs atomicity, a transaction, or equivalent coordination.

Q31. A programming language supports both functional expressions and mutable variables. What determines whether a particular function avoids synchronization problems from shared mutation?

A.Whether the source file has a functional-language extension.
B.Whether the function is compiled with optimization enabled.
C.Whether the function and the data it uses actually avoid externally visible mutation, not merely the language's label. βœ…
D.Whether the function contains at least one recursive call.
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: A language may offer functional and imperative features together. Concurrency benefits arise when the code uses pure functions and immutable data; mutable shared state can reintroduce races regardless of the language label.

Q32. Two pure functions operate on the same immutable input, but the second requires the first function's output. Does immutability make them safe to execute simultaneously?

A.Yes. Immutable inputs remove every data dependency between functions.
B.Yes. The scheduler can infer the second result from the input alone.
C.No. Pure functions must always execute on a single thread.
D.No. Immutability prevents mutation races, but the second computation still depends on the first result and must wait for it. βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: Immutability prevents conflicting updates to shared data, but it does not remove a true producer-consumer dependency. The second function cannot begin its dependent calculation until the first result exists.

Q33. A server uses a shared in-memory cache that workers update in place. The team wants a functional style for concurrent reads. Which change is most appropriate?

A.Publish immutable cache snapshots and create replacement versions for updates, coordinating publication of the current version. βœ…
B.Keep mutating the same cache and assume readers will see complete updates automatically.
C.Give every worker a constant reference while allowing the cache manager to mutate the object through another alias.
D.Remove all cache reads so workers can update the same entries concurrently.
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– Explanation: Immutable snapshots let readers use stable cache versions without racing with in-place changes. The system must still coordinate which new version becomes current, but readers need not lock the snapshot contents.

Q34. A system shares immutable job descriptions safely, but workers send completion notifications to a monitoring service that requires notifications in job order. What still needs coordination?

A.The immutable descriptions must be locked for every read.
B.The notification sequence must be ordered even though reading the shared job descriptions is safe. βœ…
C.The functional calculations must be changed to mutate each job description.
D.No coordination is needed because immutable values order external messages automatically.
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: Immutability protects the shared descriptions from write races, but it does not impose an order on external notifications. A sequencer or ordered queue must enforce the monitoring service's required order.

Q35. A system replaces every in-place update with a new immutable copy of a large structure. What is a realistic trade-off the designer should evaluate?

A.Immutable structures always require more mutexes than mutable structures.
B.Creating a new value guarantees constant-time updates for every data structure.
C.Reduced synchronization and simpler reasoning may be offset by allocation, copying, memory use, or garbage-collection overhead. βœ…
D.Immutability prevents the system from sharing any data between threads.
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: Immutability can reduce locking and make concurrent reasoning simpler, but constructing versions may consume memory and processing time. Persistent data structures and structural sharing can reduce, but not erase, those costs.

Q36. Two workers read the same immutable account state with balance 100. One returns a new state with a deposit of 20; the other returns a new state with a fee of 5. The intended final balance must include both operations. What is required?

A.Accept whichever worker finishes last, producing either 120 or 95.
B.Assume the two immutable results automatically combine into 115 without additional logic.
C.Discard the starting state and add the two resulting balances to obtain 215.
D.Apply both changes through a defined merge or ordered state-transition step, producing balance 115. βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: The workers independently produce balances 120 and 95 from the same original snapshot, so selecting either loses an operation. Merge the deposit and fee deltas: 100 + 20 βˆ’ 5 = 115, preserving both requested changes.

πŸ”— Related Topics (MCQs)