我获得了大学任务,无需繁忙等待即可实施互斥锁。我正在努力实现它,但没有取得多大成功。有时,它会抛出分段溢出,但是它只是一直悬挂,但是当我在gdb中运行时它每次运行都很完美。
mutex.c
#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;
}
stack.h
#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;
}
答案 0 :(得分:0)
不会同步从互斥锁实施中访问您的Stack
数据结构。
多个线程可以同时尝试acquire
互斥锁,这将导致它们同时访问waiting_q
。同样,发布线程对pop()
的{{1}}访问权限与获取线程的waiting_q
访问权限不同步。
push()
上的这一数据竞赛最有可能导致段错误。