| 202 | std::atomic<int> str_test_start_barrier = 0; |
| 203 | |
| 204 | auto spinlock_smp_string_test() -> bool { |
| 205 | size_t core_id = cpu_io::GetCurrentCoreId(); |
| 206 | size_t core_count = BasicInfoSingleton::instance().core_count; |
| 207 | |
| 208 | if (core_count < 2) { |
| 209 | if (core_id == 0) { |
| 210 | klog::Info("Skipping SMP string test: need more than 1 core."); |
| 211 | } |
| 212 | return true; |
| 213 | } |
| 214 | |
| 215 | int arrived = str_test_start_barrier.fetch_add(1) + 1; |
| 216 | |
| 217 | constexpr int kBarrierSpinLimit = 100000000; |
| 218 | int spins = 0; |
| 219 | while (str_test_start_barrier.load(std::memory_order_acquire) < |
| 220 | (int)core_count) { |
| 221 | cpu_io::Pause(); |
| 222 | if (++spins > kBarrierSpinLimit) { |
| 223 | if (core_id == 0) { |
| 224 | klog::Err( |
| 225 | "SMP string test barrier timeout: {}/{} cores arrived, skipping", |
| 226 | str_test_start_barrier.load(), (int)core_count); |
| 227 | } |
| 228 | return false; |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | int writes_per_core = 500; |
| 233 | char local_buf[128]; |
| 234 | |
| 235 | for (int i = 0; i < writes_per_core; ++i) { |
| 236 | // 2. 先写入可区分的字符串到本地缓冲区 |
| 237 | // 增加数据长度以增加临界区持续时间 |
| 238 | auto* end = etl::format_to_n(local_buf, sizeof(local_buf) - 1, |
| 239 | "[C:{}-{}|LongStringPaddingForContention]", |
| 240 | (int)core_id, i); |
| 241 | *end = '\0'; |
| 242 | int len = static_cast<int>(end - local_buf); |
| 243 | |
| 244 | (void)str_lock.Lock(); |
| 245 | if (str_buffer_offset + len < STR_BUFFER_SIZE - 1) { |
| 246 | for (int k = 0; k < len; ++k) { |
| 247 | shared_str_buffer[str_buffer_offset + k] = local_buf[k]; |
| 248 | } |
| 249 | str_buffer_offset += len; |
| 250 | shared_str_buffer[str_buffer_offset] = '\0'; |
| 251 | } |
| 252 | (void)str_lock.UnLock(); |
| 253 | } |
| 254 | |
| 255 | int finished = str_test_finished_cores.fetch_add(1) + 1; |
| 256 | if (finished == (int)core_count) { |
| 257 | // 3. 验证 |
| 258 | klog::Info( |
| 259 | "All cores finished string writes. Verifying string integrity..."); |
| 260 | bool failed = false; |
| 261 | int current_idx = 0; |
no test coverage detected