<分区>
我正在尝试通过使用 Windows API 的 EnterCriticalSection
和 LeaveCriticalSection
进行同步,为 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 的帮助和我的小补充下,这个流现在应该是线程安全的了。
问候