Skip to content

Instantly share code, notes, and snippets.

@mbs0221
Last active November 20, 2023 17:01
Show Gist options
  • Select an option

  • Save mbs0221/e440938c66d0177c9e4744fc8469d51d to your computer and use it in GitHub Desktop.

Select an option

Save mbs0221/e440938c66d0177c9e4744fc8469d51d to your computer and use it in GitHub Desktop.
simple Intel TSX example
#include <stdio.h>
#include <immintrin.h>
int main() {
unsigned int balance = 100;
unsigned int withdrawal = 50;
// 开始事务
if (_xbegin() == _XBEGIN_STARTED) {
// 在事务中执行操作
if (balance >= withdrawal) {
balance -= withdrawal;
printf("取款成功!余额:%u\n", balance);
// 提交事务
_xend();
} else {
// 事务中止,回滚操作
_xabort(0);
}
} else {
// 事务中止,执行备用操作
balance -= withdrawal;
printf("取款失败!余额不足,余额:%u\n", balance);
}
return 0;
}

Intel TSX

Sample C++ code for using Intel TSX (Transactional Synchronization Extensions) on Linux.

#include <immintrin.h>
#include <iostream>

int main() {
    int lockVar = 0;

    if (__sync_bool_compare_and_swap(&lockVar, 0, 1)) {
        // Critical section
        std::cout << "Transactionally executing\n";
        __sync_lock_release(&lockVar);
    } else {
        // Fallback path
        std::cout << "Transaction aborted, using fallback path\n";
    }
    return 0;
}

Or, using _xbegin and _xend:

#include <immintrin.h>
#include <iostream>

int main() {
    int lockVar = 0;

    if (_xbegin() == _XBEGIN_STARTED) {
        if (lockVar != 0) {
            _xabort(0xff);
        }
        // Critical section
        std::cout << "Transactionally executing\n";
        _xend();
    } else {
        // Fallback path
        std::cout << "Transaction aborted, using fallback path\n";
    }

    return 0;
}

Compile with:

g++ -mrtm -o tsx tsx.c

For more information, see the Intel TSX Programming Guide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment