c++ - 线程安全的 std::cout 死锁

标签 c++ multithreading

<分区>

我正在尝试通过使用 Windows API 的 EnterCriticalSectionLeaveCriticalSection 进行同步,为 std::cout 实现一个简单的、线程安全的解决方法。 我认为示例代码是不言自明的,所以我们开始吧:

#include <cstdlib>
#include <iostream>
#include <windows.h>

namespace mynamespace {

class MyStream {
    public:
        MyStream(void) : m_lockOwner(0) {
            ::InitializeCriticalSection(&m_lock);
        }

        ~MyStream(void) {
            ::DeleteCriticalSection(&m_lock);
        }


        template <typename T>
        MyStream& operator<<(const T& x) {
            Lock();
            std::cout << x;

            return *this;
        }

        void Lock() {
            ::EnterCriticalSection(&m_lock);  // Try to get the lock, irrelevant which thread it is
            // One thread successfully received the lock and entered the critical section
            if(m_lockOwner == ::GetCurrentThreadId()) {
                // Decrease the lock count of a thread when it entered multiple times the critical section
                // e.g. mynamespace::stream << "critsec1" << "critsec2"; mynamespace::stream << mynamespace::endl;
                ::LeaveCriticalSection(&m_lock);
            }
            // Store the thread ID of the thread that holds the lock at the moment
            m_lockOwner = ::GetCurrentThreadId();
        }

        void Unlock() {
           if(m_lockOwner == GetCurrentThreadId()) {
               // Release the lock only if the calling thread is the owner
               // Note: This should be the last decrease of the lock count

               // Also reset the ownership of the lock,
               // e.g. for the case that one thread is able to enter the critical section two times in a row
               // mynamespace::stream << "crit first" << mynamespace::endl;
               // mynamespace::stream << "crit second" << mynamespace::endl;
               m_lockOwner = 0;
               ::LeaveCriticalSection(&m_lock);
           }
        }

        MyStream& operator<<(MyStream& (*endl)(MyStream&)) {
            return endl(*this);
        }

        DWORD            m_lockOwner;
        CRITICAL_SECTION m_lock;
    };

    static MyStream& endl(MyStream& stream) {
        std::cout << std::endl;
        stream.Unlock();
        return stream;
    }

    MyStream stream;

};

bool alive = true;

DWORD my_thread(LPVOID t) {
    while(alive) {
        mynamespace::stream << "OWN THREAD" << mynamespace::endl;
    }

    return 0;
}

void waitForThread(HANDLE th) {
    alive = false;

    // Wait for thread to finish
    (void)::WaitForSingleObject(th, INFINITE);

    ::CloseHandle(th);

    th = 0;
}

int main(void) {
    HANDLE th = ::CreateThread(
        NULL,
        0,
        reinterpret_cast<LPTHREAD_START_ROUTINE>(&my_thread),
        NULL,
        0,
        NULL);

    mynamespace::stream << "test print 1" << "test print 2";
    mynamespace::stream << mynamespace::endl;
    mynamespace::stream << "test print 3";
    ::Sleep(10);
    mynamespace::stream << mynamespace::endl;
    ::Sleep(10);

    waitForThread(th);

    return EXIT_SUCCESS;
}

在我的第一篇文章中,我提到我在退出程序时有时会遇到死锁。

这里的问题是我调用LeaveCriticalSection 的次数不如我通过一个线程进入临界区那么频繁。 另一个问题是我没有正确退出子线程。

在 egurs 的帮助和我的小补充下,这个流现在应该是线程安全的了。

问候

最佳答案

你进入临界区多次,增加了它的引用计数,但是当你调用endl时你释放它一次所以临界区仍处于锁定状态。

在您的类中存储一个线程 ID,以了解该线程拥有锁。 进入临界区,比较线程ID。等于 -> 这不是第一个锁,因此您需要调用 LeaveCriticalSection 否则更新线程 ID 变量。

class MyStream {
...
     void Lock() {
         WaitForCriticalSection(&m_lock);
     }
     DWORD  m_EventOwner;
};

编辑

从原始答案更改了我的解决方案的机制。

这是工作代码:

namespace mynamespace {

class MyStream {
    public:
        MyStream(void) {
            InitializeCriticalSection(&m_lock);
        }

        ~MyStream(void) {
            DeleteCriticalSection(&m_lock);
        }


        template <typename T>
        MyStream& operator<<(const T& x) {
            Lock();
            std::cout << x;

            return *this;
        }

        void Lock() {
            EnterCriticalSection(&m_lock);
            if (m_eventOwner == GetCurrentThreadId()) {
                LeaveCriticalSection(&m_lock);
            }
        }

        void Unlock() {
            if (m_eventOwner != GetCurrentThreadId()) {
                //error!
            }
            LeaveCriticalSection(&m_lock);
        }

        MyStream& operator<<(MyStream& (*endl)(MyStream&)) {
            return endl(*this);
        }

        DWORD  m_eventOwner;
        CRITICAL_SECTION m_lock;
    };

    static MyStream& endl(MyStream& stream) {
        std::cout << std::endl;
        stream.Unlock();
        return stream;
    }

    MyStream stream;

};

关于c++ - 线程安全的 std::cout 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20576031/

相关文章:

multithreading - Delphi:在主线程之外创建和使用套接字

c++ - 是大括号可构造的类型特征

C++ 初始化结构体 vector 的正确方法

python - 使用pyqtgraph使用外部数据进行绘图

java网络接受线程之间的网络连接

iOS线程调用

java - 再次设置 AtomicBoolean

c++ - 从 Visual Studio 6 升级有哪些令人信服的论据?

c++ - 将模板从类特化为整数

c++ - 在 ';' 之前缺少 'using'