Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic execution of a statement block

I have a sequence of statements that I want to run atomically. For simplicity let's say they are enclosed in a block statement:

{
    // statements...
}   

Is there any straightforward way to do such a thing in C++14?

To clarify, I want this block to be executed as if it is only one atomic operation. I don't have a critical section to protect with a mutex. The problem is that the bundled operations should get executed after each other without multiple context switches between the first and the last statements in the sequence.

like image 610
Ahmad Siavashi Avatar asked Mar 11 '23 03:03

Ahmad Siavashi


2 Answers

Depends what you mean by "straightforward". I think std::unique_lock is pretty straightward to use.

{
    std::unique_lock lock(m_mutex);
    // sequence of operations

    // lock destructor will release mutex
}

The only problem is that any other places that manipulate the variables protected by the mutex must also do the same.

Edit

To answer the clarified question: No.

To prevent context switches you will have to use a proper Real Time Operating System (RTOS), and use its facilities. If you are running under a general purpose OS like Linux or Windows (the visual-studio tag suggests the latter), there are various platform specific calls you can make which will make context switches less likely - but you can't prevent them.

(Context switches become less likely if you run in kernel-mode, but even then it's hard to stop interrupt handlers and page-fault handlers cutting in.)

like image 66
Martin Bonner supports Monica Avatar answered Mar 20 '23 01:03

Martin Bonner supports Monica


The issue is: Transactional memory. A transaction is an action that has the properties Atomicity, Consistency, Isolation, and Durability (ACID). Atomicity: Either all or no statement of the block is performed. Consistency: The system is always in a consistent state. All transactions build a total order. Isolation: Each transaction runs in total isolation from the other transactions.

"A transaction is a kind of a speculative action that is only committed if the initial state holds. It is in contrast to a mutex an optimistic approach. A transaction is performed without synchronisation. It will only be published if no conflict to its initial state happens. A mutex is a pessimistic approach. At first, the mutex ensures that no other thread can enter the critical region. The thread only will enter the critical region if it is the exclusive owner of the mutex and, hence, all other threads are blocked." - Rainer Grimm

Transactional memory is supported by GCC as of version 6.1 (requires -fgnu-tm to enable). (reference)

like image 41
Amit G. Avatar answered Mar 20 '23 03:03

Amit G.