【发布时间】:2014-03-31 11:10:50
【问题描述】:
我正在尝试使用 fsync() 和 write() 编写程序,但 fsync 需要时间来同步数据,但我没有时间等待。我又为 fsync() 做了一个线程 这是我的代码:
#include <thread>
void thread_func(int fd) {
while (1) {
if(fsync(fd) != 0)
std::cout << "ERROR fsync()\n";
usleep(100);
}
}
int main () {
int fd = open ("device", O_RDWR | O_NONBLOCK);
if (fd < 0) {
std::cout << "ERROR: open()\n";
return -1;
}
std::thread *thr = new std::thread (thread_func, fd);
if (thr == nullptr) {
std::cout << "Cannot create thread\n";
close (fd);
return -1;
}
while (1) {
if (write (fd, 'x', 1) < 1)
std::cout << "ERROR write()\n";
}
close(fd);
}
问题是:
当我使用文件描述符在除主线程之外的其他线程中进行 fsync 时,是否需要锁定不同的线程? 当我在没有互斥锁的情况下测试我的程序时,它没有问题。当我阅读 fsync 的 man 描述时,它对不同的线程没有任何作用。
【问题讨论】: