1

我在下面的代码中编写了服务器从套接字上的客户端获取请求并为每个客户端创建一个线程的代码。然后每个客户端线程写入所有线程共有的文件。open该文件在 main 启动时已被编辑,因此每个线程都使用相同的 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 天前发布了它,但没有任何评论。

4

1 回答 1

0

以我的拙见,让每个写入线程直接访问文件描述符并不是一个很好的做法。我认为最好创建一个文件编写器代理来管理和管理对文件的所有写入,并将该代理传递给每个客户端。然后,您可以在客户端线程和文件代理(可能在其自己的线程上)之间设置队列机制,从而将客户端对象与写入文件逻辑和处理完全分开并保持更好的封装。

于 2013-10-21T07:24:42.130 回答