| 69 | } |
| 70 | |
| 71 | void ReadWrite::execute() { |
| 72 | // This function should produce a string that consists of 1 character type. |
| 73 | work.resize(1 + rand.upTo(MAX_WORK)); |
| 74 | |
| 75 | for (int i = 0; i < work.size(); i++) { |
| 76 | work[i] = rand.getSingleSymbolString(FILE_SIZE); |
| 77 | } |
| 78 | // Generate a test file to read and write to. |
| 79 | fd = open("test", O_CREAT | O_RDWR, 0777); |
| 80 | assert(fd != -1); |
| 81 | |
| 82 | // Populate the file with initial data. |
| 83 | assert(pwrite(fd, work.begin()->c_str(), work.begin()->size(), 0) != -1); |
| 84 | |
| 85 | // Create writer threads. |
| 86 | std::vector<std::thread> writers; |
| 87 | std::vector<std::thread> readers; |
| 88 | |
| 89 | for (int i = 0; i < NUM_WRITERS; i++) { |
| 90 | std::thread th(&ReadWrite::writer, this); |
| 91 | writers.emplace_back(std::move(th)); |
| 92 | } |
| 93 | |
| 94 | for (int i = 0; i < NUM_READERS; i++) { |
| 95 | std::thread th(&ReadWrite::reader, this); |
| 96 | readers.emplace_back(std::move(th)); |
| 97 | } |
| 98 | |
| 99 | // This atomic bool ensures that all threads have an equal chance of |
| 100 | // starting first. |
| 101 | go.store(true); |
| 102 | |
| 103 | std::this_thread::sleep_for(std::chrono::seconds(DURATION)); |
| 104 | |
| 105 | // Stop file operations after pre-defined duration. |
| 106 | stop.store(true); |
| 107 | |
| 108 | for (auto& th : writers) { |
| 109 | th.join(); |
| 110 | } |
| 111 | |
| 112 | for (auto& th : readers) { |
| 113 | th.join(); |
| 114 | } |
| 115 | |
| 116 | // Clean up files. |
| 117 | unlink("test"); |
| 118 | close(fd); |
| 119 | } |
| 120 | } // namespace wasmfs |