【问题标题】:C: File locking between threadsC:线程之间的文件锁定
【发布时间】:2013-10-21 05:10:24
【问题描述】:

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

【问题讨论】:

    标签: c multithreading sockets file-locking


    【解决方案1】:

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

    【讨论】:

    • 这个代理的东西是标准术语吗?抱歉,但不知道这个术语,所以想问一下该代理将是什么......一个单独的管理线程的单独功能?
    • @Diwakar Sharma 抱歉,出于某种原因,我没有注意到您使用的是纯 C 而不是面向对象的语言,因此这并不适用于您的情况。我的错。
    猜你喜欢
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多