How can i set the imported memory to accept shared memory in clang



  • Hi I want to do a simple WASM multi thread test(in c), but I cannot get shared memory to work. I'm using plain clang. This is what I tried so far
    Compiled with:

    clang++ src/*.cpp -Oz -c -Wall --target=wasm32 -fvisibility=hidden -pthread 
    wasm-ld *.o --no-entry --allow-undefined --strip-all --export-dynamic --import-memory --import-table -o test.wasm
    

    JavaScript memory declaration:

    const memory = new WebAssembly.Memory( { initial: memory_init_pages,shared: true, maximum:64} );	// 
    

    error MSG:

    LinkError: WebAssembly Instantiation: mismatch in shared state of memory, declared = 0, imported = 1
    

    my c++ programm just writes to memory at a given address and check if it worked



  • @K0IN Glad to hear!



  • Never mind (solved it) got it to work you need to set the link flag "--shared-memory"

    "C:/Program Files/LLVM/bin/wasm-ld" *.o --no-entry --allow-undefined --strip-all --export-dynamic --import-memory --shared-memory --import-table --strip-debug --max-memory=1310720 -o test.wasm
    

    also, you need to set --max-memory

    my test project is available at https://github.com/K0IN/WebassemblySimpleMultithreading



  • main.cpp

     __attribute__((visibility("default"))) extern "C" int set( int adr, int value) {	
    	*(int*)adr = value;
      	return *(int*)adr;
    }
    

    Clang emits:

    (module
      (type $t0 (func (param i32 i32) (result i32)))
      (import "env" "memory" (memory $env.memory 2))
      (import "env" "__indirect_function_table" (table $env.__indirect_function_table 1 anyfunc))
      (func $set (type $t0) (param $p0 i32) (param $p1 i32) (result i32)
        get_local $p0
        get_local $p1
        i32.store
        get_local $p1)
      (global $g0 (mut i32) (i32.const 66560))
      (global $__heap_base i32 (i32.const 66560))
      (global $__data_end i32 (i32.const 1024))
      (export "__heap_base" (global 1))
      (export "__data_end" (global 2))
      (export "set" (func $set)))
    
    

    according to https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md
    the memory type should be "shared" but isn't how can I enable that (is there a link flag for that?)

    What i want to do:
    In the main thread I write to __heap_base + 10 (an exported variable by clang) just some random values and in the worker I want to do the same on __heap_base + 14 I do the same and later check in js if the memory changed

    The program works on single thread but I cannot load shared memory.

    (also yes I enabled sharedarraybuffer in chrome)


  • Global Moderator

    Can you please show me your c/c++ source code?


Log in to reply
 

SUGGESTED TOPICS

A community for developers looking to put WebAssembly to use today. Come rock WebAssembly with us!