Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Simple, crude mutex test
- by: Chris M. Thomasson
- __________________________________________*/
- #include <thread>
- #include <atomic>
- #include <mutex>
- #include <condition_variable>
- #include <iostream>
- #include <functional>
- #include <cassert>
- #include <cstdlib>
- #include <ctime>
- #define THREADS 16UL
- #define ITERS 10000000UL
- #define COUNT (THREADS * ITERS)
- // undefine to test std::mutex
- #define CT_TEST_FAST_MUTEX 1
- // bin-sema
- struct ct_auto_reset_event
- {
- bool m_state;
- std::mutex m_mutex;
- std::condition_variable m_cond;
- ct_auto_reset_event() : m_state(false) {}
- void signal()
- {
- std::unique_lock<std::mutex> lock(m_mutex);
- m_state = true;
- m_cond.notify_one();
- }
- void wait()
- {
- std::unique_lock<std::mutex> lock(m_mutex);
- while (m_state == false) m_cond.wait(lock);
- m_state = false; // auto-reset
- }
- };
- // just a layer over an auto-reset event
- struct ct_fast_mutex
- {
- std::atomic<unsigned int> m_state;
- ct_auto_reset_event m_waitset;
- ct_fast_mutex() : m_state(0) {}
- void lock()
- {
- if (m_state.exchange(1, std::memory_order_acquire))
- {
- while (m_state.exchange(2, std::memory_order_acquire))
- {
- m_waitset.wait();
- }
- }
- }
- void unlock()
- {
- if (m_state.exchange(0, std::memory_order_release) == 2)
- {
- m_waitset.signal();
- }
- }
- };
- struct ct_shared
- {
- std::atomic<unsigned long> m_state;
- #if defined (CT_TEST_FAST_MUTEX)
- ct_fast_mutex m_std_mutex;
- #else
- std::mutex m_std_mutex;
- #endif
- ct_shared() : m_state(0) {}
- };
- void ct_thread(ct_shared& shared, std::size_t index)
- {
- for (unsigned int i = 0; i < ITERS; ++i)
- {
- shared.m_std_mutex.lock();
- if (i % 256 == 0) std::this_thread::yield();
- shared.m_state += 1;
- shared.m_std_mutex.unlock();
- }
- }
- int main()
- {
- ct_shared shared;
- {
- std::thread threads[THREADS];
- std::clock_t start = std::clock();
- for (std::size_t i = 0; i < THREADS; ++i)
- {
- threads[i] = std::thread(ct_thread, std::ref(shared), i);
- }
- for (std::size_t i = 0; i < THREADS; ++i)
- {
- threads[i].join();
- }
- std::clock_t diff = clock() - start;
- unsigned long msec = diff * 1000 / CLOCKS_PER_SEC;
- std::cout << "msec = " << msec << "\n";
- }
- std::cout << "shared.m_state = " << shared.m_state << "\n";
- std::cout << "\n\nFin!\n";
- assert(shared.m_state == COUNT);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment