Sobes.tech
Junior — Middle

Can you give an example of an operation that is performed as a single unit without interference from other processes or operations?

sobes.tech AI

Answer from AI

An example of such an operation is a transaction in a database. A transaction is executed as a single unit — either all changes are applied, or none, ensuring data integrity.

In Python, using the SQLAlchemy library, it looks like this:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()

try:
    # Start the transaction
    user = User(name='Alice')
    session.add(user)
    session.commit()  # All changes are committed simultaneously
except:
    session.rollback()  # Roll back changes in case of error
    raise
finally:
    session.close()

Such an operation is atomic and is not interrupted by other processes.