Hi all,

I am trying to write a concurrent stack. Code is below:

%{
#include <stdatomic.h>
#include <stdlib.h>

struct stack_t {
    void *value;
    struct stack_t *next;
};

void __cats_new(struct stack_t *st) {
    st->value = NULL;
    st->next = NULL;
}

void __cats_push(struct stack_t *st, void *val) {
    for (;;) {
        struct stack_t old_st = *st;
        struct stack_t new_st = {val, &old_st};
        if (atomic_compare_exchange_strong(st, &old_st, new_st))
            return;
    }
}

// ignore ABA problem
void *__cats_pop(struct stack_t *st) {
    for (;;) {
        if (st->next == NULL)
            return NULL;
        struct stack_t *old_st = st;
        struct stack_t xs1 = *(st->next);
        void *x = st->value;
        if (atomic_compare_exchange_strong(st, old_st, xs1))
            return x;
    }
}

atstype_boxed pop_ats(atstype_ref st) { return __cats_pop(st); }

atsvoid_t0ype new_ats(atstype_ref st) { __cats_new(st); }

atsvoid_t0ype push_ats(atstype_ref st, atstype_var val) {
    __cats_push(st, val);
}
%}

typedef stack_t(a: t@ype+) = $extype "struct stack_t"

extern
fun new {a:t@ype+}(&stack_t(a)? >> _) : void =
  "ext#new_ats"

extern
fun push {a:t@ype+}(&stack_t(a) >> _, a) : void =
  "ext#push_ats"

extern
fun pop {a:t@ype+}(&stack_t(a) >> _) : Option(a) =
  "ext#pop_ats"

fn print_str(x : string) : void =
  println!(x)

implement main0 (argc, argv) =
  let
    var st: stack_t(string)
    val () = new(st)
    val () = push(st, "res")
    val () = push(st, "res2")
    val- Some (x) = pop(st)
    val () = print_str(x)
  in end

(This compiles with gcc; I can run it with patscc simple.dats -latomic ;
./a.out)

Unfortunately, it immediately segfaults. I know that the offending line
is the

val () = print_str(x)

because removing it makes the program run fine.

I tried writing an equivalent program in C, viz.

#include <stdio.h>

int main(int argc, char *argv[]) {

    struct stack_t *st;

    __cats_push(st, "res");
    __cats_push(st, "res2");

    char *res;

    res = __cats_pop(st);
    printf("%s\n", res);

    res = __cats_pop(st);
    printf("%s\n", res);
}

...which works as expected. So I believe I am misunderstanding how ATS
handles FFI and how structures exist in memory. 

Any insight is appreciated!

Thanks,
Vanessa

-- 
You received this message because you are subscribed to the Google Groups 
"ats-lang-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ats-lang-users/e2453f48-e212-fb8c-fb2c-f5588128eebe%40gmail.com.

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to