美文网首页
Windows 线程同步

Windows 线程同步

作者: AD_wang | 来源:发表于2022-06-10 21:50 被阅读0次

    用户对象:简单高效,功能受限。

    内核对象:复杂,但是功能多,可指定超时,防止死锁。

    1.临界区(用户对象):适用范围是单一进程 的各线程之间。

    #include <iostream>

    #include <Windows.h>

    #include <process.h>

    using namespace std;

    const int THREAD_COUNT = 1000;//线程数量

    CRITICAL_SECTION g_CS;

    int g_count = 30;

    int g_sum = 0;

    DWORD WINAPI threadFunc(LPVOID);//线程函数前向声明

    int main()

    {

        HANDLE arrThread[THREAD_COUNT];

        InitializeCriticalSection(&g_CS);//初始化临界区

        DWORD threadID = -1;

        for (int i = 0; i < THREAD_COUNT; ++i)

        {

            arrThread[i] = CreateThread(NULL, 0, threadFunc, NULL, 0, &threadID);

            if (!arrThread[i])

            {

                cout<<"call CreateThread() failed!"<<endl;

                return -1;

            }

        }

        WaitForMultipleObjects(THREAD_COUNT, arrThread, true, INFINITE);

        for (int i = 0; i < THREAD_COUNT; ++i)

        {

            CloseHandle(arrThread[i]);

        }

        EnterCriticalSection(&g_CS);

        cout <<g_sum<<endl;

        LeaveCriticalSection(&g_CS);

        DeleteCriticalSection(&g_CS);

        system("pause");

        return 0;

    }

    //线程函数,使用临界区的例子

    DWORD WINAPI threadFunc(LPVOID pParam)

    {

        EnterCriticalSection(&g_CS);

        ++g_sum;

        if (g_count > 0)

        {

            cout << "窗口"<< GetCurrentThreadId() << ":count-" << g_count--<<endl;

        }

        else

        {

            cout <<g_count<<endl;

        }

        LeaveCriticalSection(&g_CS);

        return 0;

    }

    2.信号量(内核对象):见另一篇文章:https://www.jianshu.com/writer#/notebooks/27831799/notes/102657179

    3.事件(内核对象)

    4.互斥量(内核对象):可以用在多个进程的线程间同步

    4.1使用CreateMutex()创建锁

    4.2使用WaitForSingleObject()锁定

    4.3使用ReleaseMutex()释放锁

    4.4使用CloseHandle()释放资源对象

    ps:内核对象,调用closehandle(对象句柄)销毁对象。

    参考链接:https://blog.csdn.net/wu_lian_nan/article/details/95066305?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-95066305-blog-102818187.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-95066305-blog-102818187.pc_relevant_antiscanv2&utm_relevant_index=1

    相关文章

      网友评论

          本文标题:Windows 线程同步

          本文链接:https://www.haomeiwen.com/subject/qbpbmrtx.html