ph ok,though nothing interesting

This commit is contained in:
ridethepig 2023-02-01 14:53:46 +00:00
parent 70a2051749
commit 2c76ba8091
2 changed files with 20 additions and 3 deletions

12
answers-thread.txt Normal file
View File

@ -0,0 +1,12 @@
Q: Why are there missing keys with 2 threads, but not with 1 thread? Identify a sequence of events with 2 threads that can lead to a key being missing.
A: Suppose K1 % NBUCKET === K2 % NBUCKET = i0
T1 put(K1);
T2 put(K2);
T1 not found
T2 not found
T1 insert(K1, V1, &table[i0], table[i0])
T2 insert(K2, V2, &table[i0], table[i0])
T1 malloc e1, e1->key = K1, e1->value = V1, e1->next = table[i0]
T2 malloc e2, e2->key = K2, e2->value = V2, e2->next = table[i0]
T1 *(&table[i0]) = e1
T2 *(&table[i0]) = e2 <---- K1 lost

View File

@ -16,7 +16,7 @@ struct entry {
struct entry *table[NBUCKET];
int keys[NKEYS];
int nthread = 1;
pthread_mutex_t lock[NBUCKET];
double
now()
@ -43,6 +43,7 @@ void put(int key, int value)
// is the key already present?
struct entry *e = 0;
pthread_mutex_lock(&lock[i]);
for (e = table[i]; e != 0; e = e->next) {
if (e->key == key)
break;
@ -54,6 +55,7 @@ void put(int key, int value)
// the new is new.
insert(key, value, &table[i], table[i]);
}
pthread_mutex_unlock(&lock[i]);
}
@ -64,10 +66,11 @@ get(int key)
struct entry *e = 0;
pthread_mutex_lock(&lock[i]);
for (e = table[i]; e != 0; e = e->next) {
if (e->key == key) break;
}
pthread_mutex_unlock(&lock[i]);
return e;
}
@ -117,7 +120,9 @@ main(int argc, char *argv[])
for (int i = 0; i < NKEYS; i++) {
keys[i] = random();
}
for (int i = 0; i < NBUCKET; i ++){
pthread_mutex_init(&lock[i], NULL);
}
//
// first the puts
//