我正在尝试使用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描述时,它对不同的线程没有任何意义。
发布于 2014-03-31 19:20:29
除非您需要线程用于其他用途,否则我建议您使用异步I/O aio库:
struct aiocb fsync_cb = {
.aio_fildes = fd
, .aio_sigevent = {
.sigev_notify = SIGEV_NONE
}
}
aio_fsync(O_SYNC, &fsync_cb);还有一个与write等效的变体。
struct aiocb write_cb = {
.aio_fildes = fd
, .aio_buf = buffer
, .aio_nbytes = nbytes
, .aio_offset = offset
, .aio_sigevent = {
.sigev_notify = SIGEV_NONE
}
}
aio_write(&write_cb);如果你选择没有任何成功的通知,那么你将不得不在某个时候检查/等待完成:
while (aio_error(&write_cb) == EINPROGRESS);https://stackoverflow.com/questions/22760084
复制相似问题