Skip to content

Instantly share code, notes, and snippets.

@XanClic
Created July 6, 2017 00:17
Show Gist options
  • Save XanClic/3db101973adc21ef49b0386db4882815 to your computer and use it in GitHub Desktop.
Save XanClic/3db101973adc21ef49b0386db4882815 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
static uint64_t loop_counter;
static bool drop_out;
uint32_t xbegin(void)
{
uint32_t result;
__asm__ __volatile__ ("xbegin 1f; mov $0xffffffff,%%eax; 1:" : "=r"(result) :: "memory");
return result;
}
void xend(void)
{
__asm__ __volatile__ ("xend" ::: "memory");
}
void inc_loop_counter(void) __attribute__((noinline))
{
loop_counter += 1;
}
void *test(void *ptr)
{
(void)ptr;
uint32_t status;
while (!drop_out) {
if ((status = xbegin()) == 0xffffffffu) {
inc_loop_counter();
xend();
} else {
drop_out = true;
return (void *)(uintptr_t)status;
}
}
return NULL;
}
int main(int argc, char *argv[])
{
int thread_counter = 2;
if (argc > 1) {
thread_counter = strtoul(argv[1], NULL, 0);
if (!thread_counter) {
fprintf(stderr, "Usage: %s [thread count]\n", argv[0]);
return 1;
}
}
pthread_t threads[thread_counter];
uint32_t result = 0;
for (int i = 0; i < thread_counter; i++) {
pthread_create(&threads[i], NULL, &test, NULL);
}
for (int i = 0; i < thread_counter; i++) {
void *tres;
pthread_join(threads[i], &tres);
if (tres) {
result = (uintptr_t)tres;
}
}
printf("%lu iterations; abort result: %x\n", loop_counter, result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment