我必須編寫一個文件服務器,允許使用自定義協議進行併發操作。C - 使用互斥鎖時程序崩潰或不反應
的前提條件是:
沒有全局鎖 物理文件系統不能接觸 叉/ SHM或並行線程必須使用。
我雖然關於以下概念:
我正在使用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
任何提示,將不勝感激。
親切的問候
你初始化互斥量了嗎? – sunny1304
是的,我已經初始化了處理函數中的互斥量。 這個項目的源代碼是 https://github.com/fish-guts/concurrent –