linux c++ 多线程 互斥访问

from: http://blog.csdn.net/chexlong/article/details/7058283
//锁接口类  
class ILock  
{  
public:  
    virtual ~ILock() {}  
  
    virtual void Lock() const = 0;  
    virtual void Unlock() const = 0;  
};  
  
//互斥锁类  
class CMutex : public ILock  
{  
public:  
    CMutex();  
    ~CMutex();  
  
    virtual void Lock() const;  
    virtual void Unlock() const;  
  
private:  
    mutable pthread_mutex_t m_mutex;  
};
//锁  
class CMyLock  
{  
public:  
    CMyLock(const ILock&);  
    ~CMyLock();  
  
private:  
    const ILock& m_lock;  
};  

//动态方式初始化互斥锁
CMutex::CMutex()
{
    pthread_mutex_init(&m_mutex, NULL);
}

//注销互斥锁
CMutex::~CMutex()
{
    pthread_mutex_destroy(&m_mutex);
}

//确保拥有互斥锁的线程对被保护资源的独自访问
void CMutex::Lock() const
{
    pthread_mutex_lock(&m_mutex);
}

//释放当前线程拥有的锁,以使其它线程可以拥有互斥锁,对被保护资源进行访问
void CMutex::Unlock() const
{
    pthread_mutex_unlock(&m_mutex);
}

//利用C++特性,进行自动加锁
CMyLock::CMyLock(const ILock& m) : m_lock(m)
{
    m_lock.Lock();
}

//利用C++特性,进行自动解锁
CMyLock::~CMyLock()
{
    m_lock.Unlock();
}

//创建一个互斥锁
CMutex g_Lock;


//线程函数
void * StartThread(void *pParam)
{
    char *pMsg = (char *)pParam;
    if (!pMsg)
    {
        return (void *)1;
    }

    //对被保护资源(以下打印语句)自动加锁
    //线程函数结束前,自动解锁
    CMyLock lock(g_Lock);

    for( int i = 0; i < 5; i++ )
    {
        cout << pMsg << endl;
        sleep( 1 );
    }

    return (void *)0;
}

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

    char *pMsg1 = "First print thread.";
    char *pMsg2 = "Second print thread.";

    //创建两个工作线程,分别打印不同的消息
    pthread_attr_init(&attr1);
    pthread_attr_setdetachstate(&attr1,PTHREAD_CREATE_JOINABLE);
    if (pthread_create(&thread1,&attr1, StartThread,pMsg1) == -1)
    {
        cout<<"Thread 1: create failed"<<endl;
    }
    pthread_attr_init(&attr2);
    pthread_attr_setdetachstate(&attr2,PTHREAD_CREATE_JOINABLE);
    if (pthread_create(&thread2,&attr2, StartThread,pMsg2) == -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);

    int iWait;
    cin>>iWait;

    return 0;
}



如果 i是一个寄存器变量或者表示一个端口数据就容易出错,所以说 volatile 可以保证对特殊地址的稳定访问。

让编译器每次操作该变量时一定要从内存中真正取出,而不是使用已经存在寄存器中的值

因为一般的对象编译器可能会将其的拷贝放在寄存器中用以加快指令的执行速度

volatile BOOL bStop = FALSE;  
//(1) 在一个线程中:
while(!bStop)  {  ...  }  
  bStop = FALSE;  
  return;    
//(2) 在另外一个线程中,要终止上面的线程循环:  
  bStop = TRUE;  
  while(bStop);

C++对象模型,反汇编实地考察C++虚函数

智能指针:引用计数,智能释放回收内存,类似JAVA。

Linux平台用C++实现信号量,同步线程。

Sockets-2.3.9.9.tar.gz



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值