WebAssembly中的多线程

10

如果您能回答有关WebAssembly多线程的问题,我将不胜感激。

我想使用两个线程(主线程和辅助线程)实现代码,使得在辅助线程中使用一个全局变量作为计数器,在循环中对其进行增量操作。主线程会在执行指令之前和之后各读取一次计数器变量的值(以测量完成该指令所需的时间)。

我已经实现了以下代码:


#include "pthread.h"
#include <stdio.h>
#include <unistd.h>
#include<chrono>

int i;
int counter;

void* timerfunction( void *ptr)
{
  printf ("Thread Timer!\n");
  //cout<<"Thread Timer!"<<endl;
  while(1)
  {
    counter=counter+1;
  }
  pthread_exit("The thread was exited!");
}




int main()
{
    pthread_t thread_id;
    void *thread_result;
    int c=0;
    int l=pthread_create(&thread_id,NULL,timerfunction,&c);
    int t1= counter;//reading the counter for the first one

    //intended instruction that we want to measure its execution time   

    int t2= counter;//reading the counter for the second one
    int t3 = t2 - t1;//computing the time
    printf ("value in the counter is: %d \n", t3);
    return 0;
}

我理解的是,Wasm对于多线程的支持不完整,因为它不能同时运行主线程和其他线程,需要类似sleep的东西来在线程之间切换。因此,我们不能在一个线程中增加计数器并在另一个线程中同时读取它。我的问题是,我的推断是否正确?如果正确,问题是什么?是来自C语言还是编译过程等?是否有任何替代方法可以使用完整的多线程?
非常感谢。

counter变量是什么?(我猜应该是g)而且不清楚如何使用g计数可以提供关于花费时间的信息...(即使没有wasm) - prog-fh
谢谢您的提示,代码已经被更正了,全局变量是计数器。实际上,我想使用这种方法作为隐式计时器,并通过读取此计数器的值来测量时间。 - user12052616
1个回答

7

你很幸运,Emscripten已经实现了带共享内存的PThreads

但是需要注意以下几点:

截至2019年9月,由于Spectre漏洞,一些浏览器已禁用SharedArrayBuffer。在这些浏览器中,您可以通过更改偏好设置来尝试使用它。在其他浏览器(如桌面版Chrome)中,默认情况下启用了SharedArrayBuffer,无需更改任何标志。

这是一种用于Specter/Meltdown攻击中创建计时器的机制

请注意,为响应Spectre漏洞,所有主要浏览器在2018年1月5日默认禁用了SharedArrayBuffer。在启用了其站点隔离功能以防范Spectre式漏洞的平台上,Chrome在v67中重新启用了它。

我没有测试过,但以下方法可能有效。

# Assuming you have a makefile, the following might work
sudo docker run --rm -v $(pwd):/src trzeci/emscripten emmake make
sudo docker run --rm -v $(pwd):/src trzeci/emscripten emcc \
src/main.o \
-s ALLOW_MEMORY_GROWTH=1 \
-s ERROR_ON_UNDEFINED_SYMBOLS=0 \
-s USE_PTHREADS=1 \

3
顺便提一下,火狐浏览器在2020年也重新启用了SharedArrayBuffers - davidanderle
但现在服务器需要跨源策略的头信息。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer - eri0o

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接