线程安全的多文件写入 [英] Thread safe multi-file writing

查看:85
本文介绍了线程安全的多文件写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接受套接字连接并读取或写入一组动态的文件,这取决于连接的性质的守护程序。因为我的守护进程是多线程的可能性是存在的同一个文件可以由多个线程写入。因为我的文件列表是动态的,不是固定不变的,我不知道如何让一个线程从碰撞到其他。由于性能的原因,我想线程同时在同一时间被写入到不同的文件,只是不相同的文件

I have a daemon that accepts socket connections and reads or writes a dynamic set of files, depending on the nature of the connection. Because my daemon is multithreaded, the possibility exists that the same file may be written to by more than one thread. Because my list of files is dynamic and not fixed, I'm not sure how to keep one thread from bumping into the other. For performance reasons, I want threads to be writing to different files at the same time, just not the same file at the same time.

其它问题建议使用互斥体,但我不完全清楚如何将互斥在这种情况下帮助 - 文件列表是动态的,只知道到线程。

Other questions have suggested using mutexes, but I'm not entirely clear how a mutex would help in this scenario - the list of files being dynamic and only known to the thread.

会使用文件锁定在这种情况下,它是适当的?如果是这样,人们将如何实现文件中的一个线程安全的方式锁定?

Would it be appropriate to use file locking in this case? If so, how would one implement file locking in a thread-safe way?

推荐答案

羊群将工作确定。它不锁定的文件描述符,它锁定的实际文件。

flock will work OK. It doesn't lock file descriptors, it locks the actual file.

这已经完全羊群'ED不能再完全由另一个进程或线程锁定的文件。这会破坏锁的全部目的。

A file that has been exclusively flock'ed can't be exclusively locked again by another process or thread. That would defeat the entire purpose of locks.

注意的一点是,这些锁​​是咨询。不使用的工艺羊群可以愉快地覆盖文件,即使另一个进程具有独占 - 羊群编辑吧。

One note is that these locks are advisory. A process that doesn't use flock can happily overwrite the file, even if another process has exclusive-flock'ed it.

这篇关于线程安全的多文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆