0

代码片段:

ofstream log;
log.open("log.txt",ios::out);
Thread threads[2];
...both threads write to the file
log.close()

当一个线程写入文件时锁定文件的任何现有设施,因此两个线程不会同时写入。谢谢。

4

2 回答 2

0

As what shang said, pwrite Performs the same action as write but writes to the specified position in the file without modifying the file pointer and therefore is safe in threads.

See man pwrite(2) for more information.

 int fd = open('some_file',O_WRONLY);
 /* in threads */
 n = pwrite(fd, write_buffer, sizeof_buffer, file_offset);

In your case, you're probably going to have to lock before writing and keep track of the offset (where you are in the file) and then release the lock to ensure race conditions don't write over existing portions of the file and all actions to and from the file play well in concurrency land.

于 2012-04-18T13:09:58.370 回答
0

您可以使用pwrite(),在多线程中写入是安全的。

于 2012-04-18T08:58:31.127 回答