[英]C: File locking between threads
我写了下面的代码,其中服务器从套接字上的客户端获取请求,并为每个客户端创建线程。 然后,每个客户端线程都将写入所有线程共有的文件。 main启动时已open
文件,因此每个线程都使用相同的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
网站上,所以我已经将其发布在三天前了,但是还没有任何评论。
以我的拙见,让每个写线程直接访问文件描述符不是一个很好的做法。 我认为最好创建一个文件编写器代理来管理和管理对文件的所有写入,并将该代理传递给每个客户端。 然后,您可以在客户端线程和文件代理之间建立队列机制(可能在其自己的线程上),从而将客户端对象与写入文件逻辑分开,并完全处理并维护更好的封装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.