Visual C++优化对大型数据集合的并发访问

http://tech.ddvip.com   2007年03月30日    社区交流

本文详细介绍Visual C++优化对大型数据集合的并发访问

  很重要的一点是您的线程类的任何数据成员都是私有的,并带有用于访问它们的 getter 和/或 setter 方法。这是因为将很可能从多个线程中访问这些数据成员,因此您需要使用封装所提供的控制来保证正确的线程同步。

  Figure 5 Thread Implementation

Thread::Thread() : m_id(0), m_h(0)
{
}
Thread::~Thread()
{
  if (m_h != 0)
  {
    wait();
    CloseHandle(m_h);
    m_id = 0;
    m_h = 0;
  }
}
void Thread::start()
{
  if (m_h != 0)
  {
    wait();
    CloseHandle(m_h);
    m_id = 0;
    m_h = 0;
  }
  unsigned id;
  unsigned long h = _beginthreadex(0, 0, entryPoint, this,
    CREATE_SUSPENDED, &id);
  if (h == 0)
  {
    throw Exception(Exception::k_threadCreationFailure);
  }
  m_id = id;
  m_h = reinterpret_cast<HANDLE>(h);
  if (ResumeThread(m_h) == static_cast<DWORD>(-1))
  {
    throw Exception(Exception::k_threadResumeFailure, GetLastError());
  }
}
unsigned __stdcall Thread::entryPoint(void* pArg)
{
  try
  {
    Thread* pThis = static_cast<Thread*>(pArg);
    pThis->run();
  }
  catch (const Exception& e)
  {
    cout << "Thread " << e.getErrorMsg() << endl << endl;
  }
  catch (const exception& e)
  {
    cout << "std::exception in thread: " << e.what() << endl << endl;
  }
  return 0;
}
bool Thread::wait(unsigned long timeout)
{
  bool result = true;
  if (m_h != 0)
  {
    switch (WaitForSingleObject(m_h, timeout))
    {
    case WAIT_OBJECT_0:
      break;
    case WAIT_TIMEOUT:
      result = false;
      break;
    default:
      throw Exception(Exception::k_threadWaitFailure,
        GetLastError());
      break;
    }
  }
  return result;
}

  图 5

作者:Ian Emmons    责编:豆豆技术应用

正在加载评论...