What is a ...
What is a ...
A data race occurs in concurrent programming when two or more threads access the same memory location concurrently, and at least one of the accesses is a write operation, without proper synchronization mechanisms in place to control the order of access. This can lead to unpredictable and undefined behavior because the outcome depends on the timing of the threads' execution, which is non-deterministic.
Consider two threads, Thread A and Thread B, both accessing a shared variable x
:
x = x + 1
x = x - 1
If these operations are not synchronized, the final value of x
can be inconsistent and depend on the order in which the threads execute their instructions. This can lead to a situation where the value of x
is not what either thread intended.
#include <pthread.h>
#include <stdio.h>
int sharedVar = 0;
pthread_mutex_t lock;
void* increment(void* arg) {
pthread_mutex_lock(&lock);
sharedVar++;
pthread_mutex_unlock(&lock);
return NULL;
}
void* decrement(void* arg) {
pthread_mutex_lock(&lock);
sharedVar--;
pthread_mutex_unlock(&lock);
return NULL;
}
int main()...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào