Linux平台用C++封装线程读写锁(2)

下边是测试代码

// pthread_rwlock.cpp : 定义控制台应用程序的入口点。
//

#include "RWLockImpl.h"

//创建一个读写锁对象
CMyRWLock g_myRWLock;
volatile int g_counter = 0;

//线程函数
void * StartThread(void *pParam)
{
 int lastCount = 0;
 for (int i = 0; i < 10000; ++i)
 {
  g_myRWLock.ReadLock();
  lastCount = g_counter;
  //在读锁域,两个线程不断循环交替访问全局变量g_counter
  for (int k = 0; k < 100; ++k)
  {
   if (g_counter != lastCount)
    cout<<"the value of g_counter has been updated."<<endl;
   sleep(0);
  }
  g_myRWLock.Unlock();


  g_myRWLock.WriteLock();
  //在写锁域,只有一个线程可以修改全局变量g_counter的值
  for (int k = 0; k < 100; ++k)
  {
   --g_counter;
   sleep(0);
  }
  for (int k = 0; k < 100; ++k)
  {
   ++g_counter;
   sleep(0);
  }
  ++g_counter;
  if (g_counter <= lastCount)
   cout<<"the value of g_counter is error."<<endl;
  g_myRWLock.Unlock();
 }

return (void *)0;
}

int main(int argc, char* argv[])
{
 pthread_t thread1,thread2;
 pthread_attr_t attr1,attr2;

//创建两个工作线程
 pthread_attr_init(&attr1);
 pthread_attr_setdetachstate(&attr1,PTHREAD_CREATE_JOINABLE);
 if (pthread_create(&thread1,&attr1, StartThread,0) == -1)
 {
  cout<<"Thread 1: create failed"<<endl;
 }
 pthread_attr_init(&attr2);
 pthread_attr_setdetachstate(&attr2,PTHREAD_CREATE_JOINABLE);
 if (pthread_create(&thread2,&attr2, StartThread,0) == -1)
 {
  cout<<"Thread 2: create failed"<<endl;
 }

//等待线程结束
 void *result;
 pthread_join(thread1,&result);
 pthread_join(thread2,&result);

//关闭线程,释放资源
 pthread_attr_destroy(&attr1);
 pthread_attr_destroy(&attr2);

cout<<"the g_counter = "<<g_counter<<endl;

int iWait;
 cin>>iWait;

return 0;
}

编译,运行

运行结果与在Win32下用C++实现多线程读写锁的相同。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6d87af3aa1606062f8ae2b721f71c8e9.html