LogSeq/pages/OSTEP Code Snippets.md
2023-04-12 21:43:34 +08:00

119 lines
2.8 KiB
Markdown

- Spin Lock Implement
id:: 6436aafd-c85f-414c-8aee-acdc71e9138e
- ```c
void lock(lock_t *lock) {
while (TestAndSet(&lock->status, 1) == 1);
}
void unlock(lock_t *lock) { lock->status = 0; }
```
- Test-And-Set Code Description
id:: 6436af87-3f1b-4ee8-a2c8-4de0f1961f1a
- ```c
int TestAndSet(int *old_ptr, int new) {
int old = *old_ptr;
*old_ptr = new;
return old;
}
```
- Ticket Lock Implement
id:: 6436af5c-0000-4bfb-9a27-1d7cf0a830db
- ```C
struct lock_t{
int ticket;
int turn;
};
void lock(lock_t *lock) {
int myturn = FetchAndAdd(&lock->ticket);
// atomically allocate a ticket as the thread's turn
while (lock->turn != myturn) ;
// wait for its turn
}
void unlock(lock_t *lock) {
lock->turn += 1;
}
```
- Lock with Queue Implement
id:: 6436b05f-2873-4af4-952c-86d82685b583
- ```C
struct lock_t{
int lk;
int guard; // spin lock for the whole lock
queue_t *q; // control who gets the lock next
};
void lock(lock_t *lock) {
while (TestAndSet(&m->guard, 1) == 1) ;
if (m->lk == 0) {
m->lk = 1;
m->guard = 0;
}
else {
m->q->add(get_tid());
setpark(); // newly added
m->guard = 0;
// ---- wakeup/waiting race ----
park();
}
}
void unlock(lock_t *lock) {
while (TestAndSet(&m->guard, 1) == 1) ;
if (m->q->empty())
m->flag = 0;
else
unpark(m->q->pop()); // should not clear flag here
// Wake up Only one waiting thread
m->guard = 0;
}
```
- Producer/Consumer Solution with Condition Variable
id:: 6436b07d-9279-46bb-9c6b-985eb2324df8
- ```C
cond_t empty, fill;
mutex_t mutex;
void *producer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
Pthread_mutex_lock(&mutex);
while (count == MAX)
Pthread_cond_wait(&empty, &mutex);
put(i);
Pthread_cond_signal(&fill);
Pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
Pthread_mutex_lock(&mutex);
while (count == 0)
Pthread_cond_wait(&fill, &mutex);
int tmp = get();
Pthread_cond_signal(&empty);
Pthread_mutex_unlock(&mutex);
printf("%d\n", tmp);
}
}
```
- Producer/Consumer Solution with Semaphore
id:: 6436b15a-98b4-49be-8cdf-abefcf7e60b1
- ```C
int empty = MAX, full = 0, mutex = 1;
void *producer() {
for (int i = 0; i < loops; ++ i) {
sem_wait(&empty);
sem_wait(&mutex);
put(i);
sem_post(&mutex);
sem_post(&full);
}
}
void *consumer() {
for (int i = 0; i < loops; ++ i) {
sem_wait(&full);
sem_wait(&mutex);
int tmp = get();
sem_post(&mutex);
sem_post(&empty);
printf("%d\n", tmp);
}
}
```