[英]Implementing Mutex Lock Without Busy Waiting
我接到大學的任務,無需等待就可以實現互斥鎖。 我正在嘗試實施它,但沒有成功。 有時,它有時會一直掛起,從而引發分段溢出,但是當我在gdb中運行它時,它每次都會完美運行。
互斥體
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <stdbool.h>
#include <sys/syscall.h>
#include "stack.h"
#define NUM_THREADS 2
// shared data structure
int sum = 0;
struct Stack waiting_q;
bool mutex_locked = false;
void * got_signal(int x) { return NULL; }
void acquire()
{
bool first_time = true;
while (!__sync_bool_compare_and_swap(&mutex_locked, false, true))
{
if (first_time)
{
push(&waiting_q, pthread_self());
first_time = false;
}
printf("%ld is waiting for mutex\n", syscall(SYS_gettid));
pause();
}
printf("Mutex acquired by %ld\n", syscall(SYS_gettid));
}
void release()
{
int thread_r = pop(&waiting_q);
if (waiting_q.size != 0 && thread_r != INT_MIN)
pthread_kill(thread_r, SIGCONT);
mutex_locked = false;
printf("Mutex released by = %ld\n", syscall(SYS_gettid));
}
void * work()
{
acquire();
for (int i = 0; i < 10000; i++)
{
sum = sum + 1;
}
release();
return NULL;
}
int main()
{
init_stack(&waiting_q);
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
{
int rc = pthread_create(&threads[i], NULL, work, NULL);
if (rc != 0)
printf("Error creating thread\n");
}
for (int i = 0; i < NUM_THREADS; i++)
{
pthread_join(threads[i], NULL);
}
printf("Value of Sum = %d\n", sum);
return 0;
}
棧
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <pthread.h>
struct Node{
struct Node * next;
pthread_t x;
};
struct Stack{
struct Node * head;
int size;
};
void push(struct Stack * s, pthread_t n)
{
struct Node * new_head = malloc(sizeof(struct Node));
new_head->next = s->head;
new_head->x = n;
s->head = new_head;
s->size++;
}
pthread_t pop(struct Stack * s)
{
pthread_t rc = INT_MIN;
if (s->head != NULL)
{
rc = s->head->x;
struct Node * next = s->head->next;
free(s->head);
s->head = next;
return rc;
}
s->size--;
return rc;
}
void init_stack(struct Stack * s)
{
s->head = 0;
s->size = 0;
}
從互斥體實現對Stack
數據結構的訪問不同步。
多個線程可能試圖同時acquire
互斥體,這將導致它們同時訪問waiting_q
。 同樣,釋放線程對waiting_q
的pop()
訪問不會與獲取線程的push()
訪問同步。
Stack
上的這種數據爭用很可能是導致段錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.