C:线程之间的文件锁定
我已经编写了下面的代码,其中服务器从套接字上的客户端获取请求,并为每个客户端创建一个线程。然后,每个客户端线程都会写入一个所有线程都通用的文件。当main启动时,文件已被C:线程之间的文件锁定,c,multithreading,sockets,file-locking,C,Multithreading,Sockets,File Locking,我已经编写了下面的代码,其中服务器从套接字上的客户端获取请求,并为每个客户端创建一个线程。然后,每个客户端线程都会写入一个所有线程都通用的文件。当main启动时,文件已被打开ed,因此每个线程使用相同的fd。在这种情况下,我尝试在一个线程写入文件时锁定它。由于线程是同一进程,因此flock不能简单地锁定文件,因此使用mutex /*Logging function*/ void write_to_file(int op_fd,char *name) { flock(op_fd,LOCK_E
打开
ed,因此每个线程使用相同的fd。在这种情况下,我尝试在一个线程写入文件时锁定它。由于线程是同一进程,因此flock
不能简单地锁定文件,因此使用mutex
/*Logging function*/
void write_to_file(int op_fd,char *name)
{
flock(op_fd,LOCK_EX);
pthread_mutex_lock(&f_lck);
write(op_fd,name,20);
pthread_mutex_unlock(&f_lck);
flock(op_fd,LOCK_UN);
}
/*Client thread function*/
void *clnt_thread(void * arg)
{
int this_fd=*(int *)arg;
/*str is a continuous memory array of the size of the dat_com struct.This will be filled up initially on receive as a normal array
, but then it'll typecasted to point to struct dat_com object*/
char str[sizeof(dat_com)],str_send[25];
memset(&str,'\0',sizeof(str));
dat_com *incm_dat; // struct to contain the incoming data from client .
while(1)
{
read(this_fd,str,sizeof(str));
/*typecast to struct dat_com so that it is ready to be inserted into linked list or file.*/
incm_dat=(dat_com *)&str;
if(strncmp(str,"quit",4)==0)
break;
/*Call write to file function*/
write_to_file(o_fd,incm_dat->name);
fprintf(stderr,"Client said: %s",incm_dat->name);
/*client wants to close connection?*/
sprintf(str_send,"%s",incm_dat->name);
send(this_fd,str_send,sizeof(incm_dat->name),MSG_NOSIGNAL);
}
close(this_fd);
return 0;
}
目前,这项工作正如期进行。这样锁是一种好的做法吗?或者还有其他最佳实践吗?如果我必须将此代码用于生产,我需要做哪些不是标准实践的更改?
我知道这最好是在
codereview
网站上,所以我已经在3天前发布了,但没有任何评论。在我看来,让每个写作线程直接访问文件描述符不是一个很好的做法。我认为最好创建一个文件编写器代理来管理和管理对文件的所有写入,并将该代理传递给每个客户端。然后,您可以在客户机线程和文件代理(可能在其自己的线程上)之间设置队列机制,从而将客户机对象从写入文件逻辑中分离出来,并进行完全的处理和维护更好的封装 这个代理是标准术语吗?对不起,我不知道这个词,所以我想问一下代理是什么。。为单独的管理线程提供单独的函数?@Diwakar Sharma抱歉,出于某种原因,我没有注意到您使用的是纯C语言,而不是面向对象的语言,因此这在您的情况下并不适用。我的错。