Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can any single-threaded program be a valid multithreaded program?

I was reading the book "Java Concurrency In Practice". In second chapter, I read the statement

any single-threaded program is also a valid multithreaded program

I could not understand this statement.

Kindly share your thoughts on it so that my confusion can be cleared. Thanks in advance.

like image 385
Rahul Avatar asked Mar 08 '17 15:03

Rahul


People also ask

Can single threaded be multithreaded?

You can always run a multithreaded programming language in single thread, but you cant do the opposite. In the end they are practically two different types of programing languages.

What does it mean for a programming language to be single threaded?

A single-thread language is one with a single call stack and a single memory heap. It means that it runs only one thing at a time. A stack is a continuous region of memory, allocating local context for each executed function. A heap is a much larger region, storing everything allocated dynamically.

How can you tell if a program is multithreaded?

In taskmanager, right-click the game process and set the affinity to one core. Play a little ingame and check your fps. Then change affinity to two cores, if your fps increases then the game is (properly) multithreaded.

What does it mean for a program to be multithreaded?

Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.


1 Answers

Note that the statement doesn't imply that any correct single threaded program is also correct multi threaded program, the author simply states that it is possible to transform any single threaded program to be executed in multi-threaded environment.

However, if the program is already not correct in single threaded environment then it cannot possibly be correct in more complex multi threaded environment.

From the book:

Since any single threaded program is also a valid multithreaded program, it cannot be thread safe if it is not even correct in a single threaded environment.

If an object is correctly implemented, no sequence of operations-calls to public methods and reads or writes of public fields should be able to violate any of its invariants or post conditions. No set of operations performed sequentially or concurrently on instances of a thread safe class can cause an instance to be in an invalid state.

And this:

If the loose use of "correctness" here bothers you, you may prefer to think of a thread safe class as one that is no more broken in a concurrent environment than in a single threaded environment.

@yshavit Before you go off thinking about multithreaded correctness, make sure you at least have single-threaded correctness.

like image 97
John Avatar answered Sep 17 '22 18:09

John