#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;
}