gpt4 book ai didi

WebAssembly 中的多线程

转载 作者:行者123 更新时间:2023-12-03 12:43:55 26 4
gpt4 key购买 nike

如果您回答我关于 WebAssembly 多线程的问题,我将不胜感激。
我想用 2 个线程(主线程和辅助线程)实现代码,这样就有一个全局变量用作辅助线程中的计数器变量,并在循环中递增它。和主线程,读取计数器变量,一次在运行指令之前,一次在运行指令之后(测量完成该指令所需的时间)。
我已经实现了这个代码:

#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之类的东西来进行线程之间的切换。因此,我们不能将多线程 Wasm 用于某些目标,例如在一个线程中增加计数器并在另一个线程中同时读取它。我的问题是我的推论是真的还是假的?如果是真的,有什么问题?从 C 或编译过程还是...?是否有使用完整多线程的替代方法?
非常感谢。

最佳答案

你很幸运,Emscripten has implemented PThreads with shared memory .

有一些警告

As of Sep 2019, some browsers have disabled SharedArrayBuffer due to the Spectre set of vulnerabilities. Until it is restored you can still experiment with it if you flip a pref in those browsers. In other browsers (like Chrome on desktop), SharedArrayBuffer is fully enabled by default and you don’t need to flip any flags.



Its a mechanism to create timers used in Specter/Meltdown attacks

Note that SharedArrayBuffer was disabled by default in all major browsers on 5 January, 2018 in response to Spectre. Chrome re-enabled it in v67 on platforms where its site-isolation feature is enabled to protect against Spectre-style vulnerabilities.



我没有测试过,但以下可能有效
# 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 \

关于WebAssembly 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com