c-只有一个进程正在通过我的互斥锁,其他进程都挂起了



因此,我正在开发一个程序,该程序将允许我使用多个进程打开文件的单个实例,而不会出现死锁。因此,我的程序的关键功能如下。它基本上决定程序是否可以基于邻接图执行文件。所以这部分似乎都很好。

我遇到的问题似乎是我的互斥锁。因此,程序的执行方式基本上是决定一个进程需要完全运行,然后其他进程才能在没有死锁的情况下打开文件(这是很好的,也是预期的行为)。但一旦第一个进程完成,它就会挂起,我相信我已经将它缩小到代码顶部的pthread_mutex_lock调用。然而,正如你所看到的,我解锁了它,所以我很困惑。

这可能与我的互斥被用于共享内存块有关吗?我无法想象这会引起问题,我真的没有其他办法。我也尝试了同样的方法,使用信号灯,但没有成功。如有任何帮助,我们将不胜感激。

FILE *openFile(char *path, char *mode) {
int segId = shmget(systemKey, size, S_IRUSR | S_IWUSR | IPC_CREAT);
memStruct* ourMem = (memStruct*)shmat(segId, NULL, 0);
pthread_mutex_lock(&ourMem->openMutex);//~~~~~~~~~~
int hasCycle = containsCycle(ourMem, path);

if(hasCycle == 0) {
FILE* fileToReturn = fopen(path, mode);
int positionOfFile = getFilePosition(path, ourMem);
int positionOfProcess = getProcessPosition(getpid(), ourMem);
ourMem->adjMatrix[positionOfFile][positionOfProcess] = 2;
ourMem->Available[positionOfFile] = 0;
ourMem->fileArray[positionOfFile] = fileToReturn;
pthread_mutex_unlock(&ourMem->openMutex);//~~~~~~~~~~
return fileToReturn;
}
else {
while(1) {
hasCycle = containsCycle(ourMem, path);
if(hasCycle == 0) {
FILE* fileToReturn = fopen(path, mode);
int positionOfFile = getFilePosition(path, ourMem);
int positionOfProcess = getProcessPosition(getpid(), ourMem);
ourMem->adjMatrix[positionOfFile][positionOfProcess] = 2;
ourMem->Available[positionOfFile] = 0;
ourMem->fileArray[positionOfFile] = fileToReturn;
pthread_mutex_unlock(&ourMem->openMutex);//~~~~~~~~~~
return fileToReturn;
}
}
}

pthread_mutex_unlock(&ourMem->openMutex);//~~~~~~~~~~

return NULL;
}

事实证明,使用sem_init(&semName,1,1),我有一个0作为第二个参数,它阻止了进程间通信。

最新更新