DerivedThread.cpp
资源名称:RWLock.zip [点击查看]
上传用户:jnsxzc
上传日期:2007-01-03
资源大小:25k
文件大小:2k
源码类别:
进程与线程
开发平台:
Visual C++
- // DerivedThread.cpp: implementation of the CDerivedThread class.
- //
- //////////////////////////////////////////////////////////////////////
- #include "stdafx.h"
- #include "TestLock.h"
- #include "DerivedThread.h"
- #ifdef _DEBUG
- #undef THIS_FILE
- static char THIS_FILE[]=__FILE__;
- #define new DEBUG_NEW
- #endif
- char CDerivedThread::g_szStringToUpdate[128];
- int CDerivedThread::g_nWriteLockAccesses = 0;
- int CDerivedThread::g_nReadLockAccesses = 0;
- //---------------------------------------------------------------------
- // run() - overrides run method of base class and provides the test for
- // read-write locking of a global string.
- //
- // Exceptions : NONE
- // Return Codes : NONE
- //---------------------------------------------------------------------
- ///////////////////////////////////////////////////////////////////////
- void CDerivedThread::run()
- ///////////////////////////////////////////////////////////////////////
- {
- char szWriterMessage[64];
- char szReaderMessage[128];
- sprintf(szWriterMessage, "Last written by thread #%ld", m_lThreadId);
- sprintf(szReaderMessage, "Read by thread #%ld : ", m_lThreadId);
- int nReadMessageLen = strlen(szReaderMessage);
- if (m_bReader)
- {
- // 100-ms object test time so that write threads are not starved...
- // this delay must be viewed "as other work done by thread"
- while (WaitForSingleObject(m_hShutdownEvent, 300) != WAIT_OBJECT_0)
- {
- // Reader thread functionality
- m_pcLock->lockRead();
- InterlockedIncrement((long *)&g_nReadLockAccesses);
- // read message from global string
- sprintf(&szReaderMessage[nReadMessageLen], "%s; Read Lock Accesses %d; Write Lock Accesses %d",
- g_szStringToUpdate, g_nReadLockAccesses, g_nWriteLockAccesses);
- m_pcLock->unlockRead();
- // The list box should be protected by a mutex... but this is only a test app
- // Do NOT measure performance of read-write locks using this list box.
- m_pcListBox->AddString(szReaderMessage);
- }
- }
- else
- {
- // 1-ms object test time so that all write threads have a chance to access
- // resources... this delay must be viewed "as other work done by thread"
- while (WaitForSingleObject(m_hShutdownEvent, 20) != WAIT_OBJECT_0)
- {
- // Writer thread functionality
- m_pcLock->lockWrite();
- g_nWriteLockAccesses++;
- memset(g_szStringToUpdate, 0, strlen(g_szStringToUpdate));
- // copy writer message to global string
- strcpy(g_szStringToUpdate, szWriterMessage);
- m_pcLock->unlockWrite();
- }
- }
- }