Xcode 13编译C++时提示notify_one、wait接口不可用的解决方案求助
问题原因
该报错是因为Xcode 13内置的Apple Clang及对应libc标准库,尚未完整实现C20引入的
std::atomic_flag的wait()、notify_one()接口,该组接口从Xcode 14及以上版本才开始正式支持。
适配方案
可根据业务场景选择以下两种常用适配方式:
方案1:使用C++11兼容的条件变量+互斥锁替换(通用场景推荐)
该方案兼容所有支持C11的编译环境,不需要依赖C20特性,逻辑稳定可靠,适配改动量小。
改后完整可运行代码:
#include <iostream> #include <atomic> #include <thread> #include <mutex> #include <condition_variable> // 替换atomic_flag为条件变量+互斥锁+状态标记的组合 std::mutex mtx; std::condition_variable cv; bool flag = false; std::atomic<int> counter{}; constexpr int countlimit = 1000000; void ping() { while(counter <= countlimit) { { std::unique_lock<std::mutex> lock(mtx); flag = true; } ++counter; cv.notify_one(); { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [&]{ return !flag; }); } } } void pong() { while(counter < countlimit) { { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [&]{ return flag; }); flag = false; } cv.notify_one(); } } int main() { auto start = std::chrono::system_clock::now(); flag = false; std::thread t1(ping); std::thread t2(pong); t1.join(); t2.join(); std::chrono::duration<double> dur = std::chrono::system_clock::now() - start; std::cout << "Duration: " << dur.count() << " seconds" << std::endl; }
方案2:无锁自旋等待实现(适合短等待的低延迟场景)
如果你的场景对性能要求极高,不想引入锁的开销,可以用自旋逻辑模拟wait效果,缺点是等待过程会占用CPU核心资源,不适合长时间等待的场景:
改后核心逻辑示例:
#include <iostream> #include <atomic> #include <thread> #if defined(__x86_64__) || defined(_M_X64) #include <immintrin.h> #endif // 用atomic<bool>替代atomic_flag实现自旋逻辑 std::atomic<bool> condAtomicFlag{false}; std::atomic<int> counter{}; constexpr int countlimit = 1000000; // 模拟wait接口 void atomic_wait(std::atomic<bool>& flag, bool expect) { while(flag.load(std::memory_order_acquire) == expect) { // 加CPU pause/yield指令降低自旋功耗,兼容x86/arm架构 #if defined(__x86_64__) || defined(_M_X64) _mm_pause(); #elif defined(__arm__) || defined(__aarch64__) __asm__ __volatile__("yield"); #endif } } void ping() { while(counter <= countlimit) { condAtomicFlag.store(true, std::memory_order_release); ++counter; atomic_wait(condAtomicFlag, true); } } void pong() { while(counter < countlimit) { atomic_wait(condAtomicFlag, false); condAtomicFlag.store(false, std::memory_order_release); } } int main() { auto start = std::chrono::system_clock::now(); condAtomicFlag.store(false, std::memory_order_release); std::thread t1(ping); std::thread t2(pong); t1.join(); t2.join(); std::chrono::duration<double> dur = std::chrono::system_clock::now() - start; std::cout << "Duration: " << dur.count() << " seconds" << std::endl; }
其他可选方案
如果允许升级编译环境,直接升级到Xcode 14及以上版本,即可原生支持C++20的std::atomic_flag wait/notify接口,不需要修改任何原有代码。
内容的提问来源于stack exchange,提问作者Cavoixanh
相关产品推荐
相关产品推荐

