I am trying to work with rtm transactions. I started using intrinsics to implement a simple transaction. But I found out the following line always returns zero, while for the transaction to successfully begin, it should be -1:
int status = _xbegin();
Then, I tried putting the if..else in a loop to reach this code:
#include<stdlib.h>
#include<immintrin.h>
#include<stdio.h>
void main()
{
    int status = _xbegin();
    if (status == _XBEGIN_STARTED) {
        printf("111");
        _xend();
    } else {
        printf("000");
    }
    status = _xbegin();
    if (status == _XBEGIN_STARTED) {
        printf("111");
        _xend();
    } else {
        printf("000");
    }
}
The output of the code is "000111" and I can't understand why the first transaction fails but the second one does not.
Also, if I make changes to printf inputs in the first transaction, the second transaction won't start at all and the output of the following modified code will be "0000":
#include<stdlib.h>
#include<immintrin.h>
#include<stdio.h>
void main()
{
    int status = _xbegin();
    if (status == _XBEGIN_STARTED) {
        printf("111");
        _xend();
    } else {
        printf("0");
    }
    status = _xbegin();
    if (status == _XBEGIN_STARTED) {
        printf("111");
        _xend();
    } else {
        printf("000");
    }
}
The same happens if I remove one of the printf lines, too.
I want to understand why the outputs are like this and how to fix the problem? Note that I use immintrin.h and compile using "gcc -mrtm".