Thread barrier shared between Go and C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// static void barrier_wait(int *barrier) | |
// { | |
// int v = __atomic_add_fetch(barrier, 1, __ATOMIC_SEQ_CST); | |
// if (v & 1) { | |
// v &= 2; | |
// while ((__atomic_load_n(barrier, __ATOMIC_SEQ_CST)&2) == v); | |
// } | |
// } | |
// | |
// static void other(int *barrier, int *x, int n) | |
// { | |
// for (int i = 0; i < n; i++) { | |
// if (*x) *(volatile int *)0 = 0; | |
// *x = 1; | |
// barrier_wait(barrier); | |
// barrier_wait(barrier); | |
// } | |
// } | |
import "C" | |
import ( | |
"fmt" | |
"sync/atomic" | |
) | |
func BarrierWait(barrier *int32) { | |
v := atomic.AddInt32(barrier, 1) | |
if v&1 == 1 { | |
v &= 2 | |
for atomic.LoadInt32(barrier)&2 == v { | |
} | |
} | |
} | |
func main() { | |
const n = 4_000_000 | |
var barrier, x int32 | |
go C.other((*C.int)(&barrier), (*C.int)(&x), n) | |
for i := 0; i < n; i++ { | |
BarrierWait(&barrier) | |
if x != 1 { | |
panic(x) | |
} | |
x = 0 | |
BarrierWait(&barrier) | |
} | |
fmt.Println("success") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment