| 670 | |
| 671 | |
| 672 | SC::Result snippetForFileWrite(AsyncEventLoop& eventLoop, Console& console) |
| 673 | { |
| 674 | ThreadPool threadPool; |
| 675 | SC_TRY(threadPool.create(4)); |
| 676 | //! [AsyncFileWriteSnippet] |
| 677 | // Assuming an already created (and running) AsyncEventLoop named `eventLoop` |
| 678 | // ... |
| 679 | |
| 680 | // Assuming an already created threadPool named `threadPool` |
| 681 | // ... |
| 682 | |
| 683 | // Open the file (for write) |
| 684 | FileOpen openMode; |
| 685 | openMode.mode = FileOpen::Write; |
| 686 | openMode.blocking = true; // AsyncFileWrite::Task enables using regular blocking file descriptors |
| 687 | FileDescriptor fd; |
| 688 | SC_TRY(fd.open("MyFile.txt", openMode)); |
| 689 | |
| 690 | // Create the async file write request |
| 691 | AsyncFileWrite asyncWriteFile; |
| 692 | asyncWriteFile.callback = [&](AsyncFileWrite::Result& res) |
| 693 | { |
| 694 | size_t writtenBytes = 0; |
| 695 | if(res.get(writtenBytes)) |
| 696 | { |
| 697 | console.print("{} bytes have been written", writtenBytes); |
| 698 | } |
| 699 | }; |
| 700 | // Obtain file descriptor handle |
| 701 | SC_TRY(fd.get(asyncWriteFile.handle, Result::Error("Invalid Handle"))); |
| 702 | asyncWriteFile.buffer = StringView("test").toCharSpan(); |
| 703 | // Vectorized writes: use proper start overload or set |
| 704 | // AsyncFileWrite::buffers and AsyncFileWrite::singleBuffer = false |
| 705 | |
| 706 | // Start the operation in a thread pool |
| 707 | AsyncTaskSequence asyncFileTask; |
| 708 | SC_TRY(asyncWriteFile.executeOn(asyncFileTask, threadPool)); |
| 709 | SC_TRY(asyncWriteFile.start(eventLoop)); |
| 710 | |
| 711 | // Execute another file write AFTER the previous one is finished on the same threadPool |
| 712 | AsyncFileWrite asyncWriteFileLater; |
| 713 | asyncWriteFileLater.buffer = StringView("AFTER").toCharSpan(); |
| 714 | SC_TRY(asyncWriteFileLater.executeOn(asyncFileTask, threadPool)); |
| 715 | SC_TRY(asyncWriteFile.start(eventLoop)); |
| 716 | |
| 717 | // Alternatively if the file is opened with blocking == false, AsyncFileRead can be omitted |
| 718 | // but the operation will not be fully async on regular (buffered) files, except on io_uring. |
| 719 | // |
| 720 | // SC_TRY(asyncWriteFile.start(eventLoop)); |
| 721 | //! [AsyncFileWriteSnippet] |
| 722 | SC_TRY(eventLoop.run()); |
| 723 | return Result(true); |
| 724 | } |
| 725 | |
| 726 | // clang-format on |
| 727 | } // namespace SC |