// 微软官方例程 稍微修改了下 测试刚刚好
 #define WDS printf
 #define THREAD_COUNT 20
 static volatile UINT vol = 0;
 void SimpleThreadA(void* id) {
    UINT& max = *(PUINT)id;

    for (size_t i = 0; i < max; i++)
    {
        WDS("[No.%u]%d %u", max, i, GetTickCount());
        InterlockedIncrement(&vol);
    }
 }

 // 测试安全性
 void MultiThreadTestA() {
    DWORD num;
    HANDLE threads[THREAD_COUNT];
    int args[THREAD_COUNT];
    int i;

    for (i = 0; i < THREAD_COUNT; i++) {
        args[i] = i + 1;
        threads[i] = (HANDLE)(_beginthread(SimpleThreadA, 0, args + i));
        if (threads[i] == (HANDLE)(-1))
            break;// error creating threads
    }

    // 等待所有线程运行完毕
    WaitForMultipleObjects(i, threads, true, INFINITE);

    // 检查最终结果
    WDS("VOL %s", vol == THREAD_COUNT ? "TRUE" : "FALSE");
 }

/*
* @@动态类 
* Locker原子锁
* QQ : 4seaynl
**/
class Locker {
private:
    LONG m_locker = NULL;
public:
	void Lock() {
		while (InterlockedExchange(&m_locker, 1)) YieldProcessor();
	}

	void Unlock() {
		InterlockedExchange(&m_locker, 0);
	}
}

/*
* @@动态类 
* RAII 自动锁
* QQ : 4seaynl
**/
class AutoLocker {
private:
	Locker& locker;
public:
	AutoLocker(Locker& nLocker) :locker(nLocker) { locker.Lock(); }
	~AutoLocker() { locker.Unlock(); }
};

/*
    // 不安全 已弃用 202306
    void Lock() {
        while (TRUE == m_locker) ::Sleep(1);
    InterlockedIncrement(>m_locker);

    void Unlock() {
        InterlockedDecrement(>m_locker);
    }
*/
posted on 2022-12-31 04:45  Ksa-NL  阅读(92)  评论(0编辑  收藏  举报