Multithreading in WebAssembly

Hi,
I will be grateful if you answer my question about WebAssembly multithreading.
I want to implement a code with 2 thread (a main thread and a helper one), such that there is a global variable that is used as a counter variable in the helper thread and it increment it in a loop. and the main thread, read the counter variable amount, once before running an instruction and once after that (to measure the time that takes for this instruction to be completed).
I have implemented this code:

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

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 exececution 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;

}

What I comprehended is that the supporting of Wasm from multithreading is not complete, because it does not run main thread and other ones simultaneously and it needs something like sleep to switch between threads. So we cannot use multithreaded Wasm for some goals like increasing a counter in one thread and reading it simultaneously in another one. My question is that either my inference is true or not? And if true, what is the problem? From C or compile process or ...? And is there any alternative method to use complete multithreading?
Thanks a lot.

Please use code blocks:

```
// your code here
```

As I understand it, the multithreading model for the WebAssembly virtual machine is still in a draft state, so there's not support for the standard primitive operations that are required to make traditional multithreading work. I assume you're using Emscripten for your C++ code, in which case Emscripten is using cooperative multitasking to simulate "real" threads. This, as you noted, only allows executing one thread at a time and requires threads to explicitly yield control in order for other threads to execute.

If you're targeting a Web platform, the general solution for multi-threading is Web workers. There have been some experiments in both C++ and Rust to use Web workers for true parallelism:

Most of these approaches require instantiating a new WebAssembly module for each worker, and the ability for the threads to communicate with each other is rather limited, but the threads do truly run in parallel.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.