string assign is not thread safe

本文深入探讨了使用C++进行并发编程的实践技巧,通过对比互斥锁与自旋锁的性能,展示了如何在多线程环境下保护共享资源。实验中,通过10个线程反复修改共享字符串,对比了两种锁机制的效率,揭示了自旋锁在高竞争场景下的微小优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <string.h>
#include <time.h>
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
using namespace std;
mutex g_lock;
string str(1024, 'A');
struct spin_lock {
    static void lock() {
        while (lock_.test_and_set(std::memory_order_acquire)) {
        }
    }
    static void unlock() {
        lock_.clear();
    }
    static atomic_flag lock_;
};
atomic_flag spin_lock::lock_ = ATOMIC_FLAG_INIT;
void fun(int i) {
    for (int loop = 0;loop < 100000;loop++) {
    lock_guard<mutex>lk(g_lock); // 0.635s
//  spin_lock().lock();          // 0.636s
    if (i % 2) {
        str = "123";
    }
    else {
        str = "456";
    }
    spin_lock().unlock();
    }
}
int main() {
    int n = 10;
    srand(time(0));
    vector<thread>threads;
    for (int i = 0;i < n;i++) {
        threads.emplace_back(thread(fun, i));
    }
    for (auto &th : threads) {
        th.join();
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值