gpt4 book ai didi

C - 使用互斥锁时程序崩溃或不响应

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:54 26 4
gpt4 key购买 nike

我必须编写一个允许使用自定义协议(protocol)进行并发操作的文件服务器。

先决条件是:

没有全局锁不得触及物理文件系统必须使用 forks/shm 或 pthreads。

我想到了以下概念:

我正在使用 prthreads。每个连接的客户端都会创建一个新线程。

我创建了一个结构来模拟文件:

struct _sFile {
char *filename;
size_t size;
char *content;
char *location;
sFile *next;
pthread_mutex_t *mutex;
};

sFile 的链表被用作文件系统。不需要考虑目录

对文件的每一次操作,都要设置两把锁;一个在当前文件上,一个在下一个文件上。每当我遍历文件时,锁就会一起移动。

我写了几个函数来遍历列表:

void iterator_init(iterator *it){
pthread_mutex_init(it->a->mutex,NULL);
pthread_mutex_init(it->b->mutex,NULL);
it->a=NULL;
it->b=file_list;
pthread_mutex_lock(it->b->mutex);
}

/*
* Return the next file in the list or null if at the end.
* If the end is reached, the iterator is already destoryed.
*/
sFile *iterator_next(iterator *it){
if (it->a != NULL)
pthread_mutex_unlock(it->a->mutex);
if (it->b->next==NULL)
{
pthread_mutex_unlock(it->b->mutex);
return NULL;
}

it->a=it->b;
it->b=it->b->next;
pthread_mutex_lock(it->b->mutex);
return it->b;
}

void iterator_destroy(iterator *it){
if (it->a != NULL)
pthread_mutex_unlock(it->a->mutex);
if (it->b != NULL)
pthread_mutex_unlock(it->b->mutex);
}

当我的客户端触发命令 LIST 时,我试图锁定文件。这是我的列表命令:

void cmd_list(int ac, char *av) {
iterator it;
iterator_init(&it);
sFile *list = file_list;
long num_files = file_count;
char ack[32];
sprintf(ack, "ACK %d\n", file_count);
send(client_sock, ack, (int) strlen(ack), 0);
sFile *current = list;
while ((current=iterator_next(&it))!=NULL){
send(client_sock, current->filename, strlen(current->filename), 0);
}

但是应用程序崩溃了

interator_init(&it)

在 cmd_create 函数中。

我做错了什么?有时,锁有效,但客户端无休止地等待,除非客户端停止,否则命令将发送到服务器。

整个应用的源码在

https://github.com/fish-guts/concurrent

如有任何提示,我们将不胜感激。

亲切的问候

最佳答案

您需要使用 pthread_mutex_init() 初始化互斥量在你可以使用它之前。 iterator_init() 尝试将互斥锁锁定在它作为参数获取的结构中,而不对其进行初始化。

关于C - 使用互斥锁时程序崩溃或不响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24138486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com