我正在使用 C 语言开发一个项目,该项目涉及通过覆盖 pthread.h 创建用户级线程库。我目前正在研究互斥体功能。
在我的实现中,我将互斥锁存储为结构的链接列表。我想在 pthread_mutex_init 中做的是将指针存储到 pthread_mutex_t 互斥变量中新创建的互斥锁元素的指针。不过,这可能吗?这是我的一些代码,因此您可以了解我要做什么:
typedef struct mutexList
{
int mid;
struct mutexList *prevMutex;
struct mutexList *nextMutex;
int locked;
struct queueItem *owner;
struct blockedThread *blockedHead;
struct blockedThread *blockedTail;
} mutexElement;
int mutexCounter = 0;
mutexElement *mutexHead = NULL;
mutexElement *mutexTail = NULL;
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
{
mutexElement *newMutex = (mutexElement *) malloc(sizeof(mutexElement));
fprintf(stdout, "***LOG: Creating new mutex.\n");
if(newMutex == NULL)
return ENOMEM;
newMutex->mid = mutexCounter;
mutexCounter++;
newMutex->locked = 0;
newMutex->nextMutex = NULL;
newMutex->blockedHead = NULL;
newMutex->blockedTail = NULL;
if(mutexHead == NULL)
mutexHead = newMutex;
if(mutexTail != NULL)
mutexTail->nextMutex = newMutex;
mutexTail = newMutex;
mutex = (&newMutex);
return 0;
}