WebAssembly / WebAssembly/threads
Not able to generate race condition
Nobody has claimed this yet.
- Dominant language
- WebAssembly
- Stars
- 767
- Forks
- 54
- PR merge metrics
- No merged PRs in 30d
Description
I wrote a code using pthreads where multiple threads were accessing and modifying a global variable and race condition should occur without any locking mechanism or atomic operations but it was not the case. Can anyone explain why this did not occur?
The code is as follows:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdbool.h>
#define NTHREADS 150
pthread_t tid[NTHREADS];
int counter;
pthread_mutex_t lock;
int check = 3;
void* trythis(void *arg)
{
unsigned long i = 0;
// pthread_mutex_lock(&lock);
counter += 1;
// pthread_mutex_unlock(&lock);
printf("\n Job %d has started\n", counter);
check+=1;
printf("\n Job %d has finished\n", counter);
check+=1;
return NULL;
}
int main(void)
{
int i = 0;
int error;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}
while(i < NTHREADS)
{
error = pthread_create(&(tid[i]), NULL, &trythis, NULL);
if (error != 0)
printf("\nThread can't be created :[%s]", strerror(error));
i++;
}
for(i=0;i<NTHREADS;i++){
pthread_join(tid[i],NULL);
}
pthread_mutex_destroy(&lock);
printf("%d\n",check );
return 0;
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by compiling and running the supplied pthread program, then inspect its printed counter values and final check value. Review the behavior of the shared updates and the absence of synchronization; done means providing an explanation grounded in the observed output and identifying what the example demonstrates.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c
- Domain
- operating-systems
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100