linux条件锁常见用法

线程同步实践

看下面例子

#include <iostream>
#include <string.h>
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;


class Mutex
{
private:
pthread_mutex_t m_mutex;
pthread_mutexattr_t m_mutexattr;


public:
Mutex(bool attr);
~Mutex();

void lock();
void unlock();
pthread_mutex_t* getMutex();


};
Mutex::Mutex(bool attr)
{
cout<<"Mutex"<<endl;
if(attr)
{
pthread_mutexattr_init(&m_mutexattr);
pthread_mutexattr_setpshared(&m_mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&m_mutex,&m_mutexattr);
}
else
{
pthread_mutexattr_init(&m_mutexattr);
pthread_mutexattr_setpshared(&m_mutexattr,PTHREAD_PROCESS_PRIVATE);
pthread_mutex_init(&m_mutex,&m_mutexattr);
}


}
Mutex::~Mutex()
{
cout<<"~Mutex"<<endl;
pthread_mutexattr_destroy(&m_mutexattr);
pthread_mutex_destroy(&m_mutex);
}


void Mutex::lock()
{
pthread_mutex_lock(&m_mutex);
}


void Mutex::unlock()
{
pthread_mutex_unlock(&m_mutex);
}


pthread_mutex_t* Mutex::getMutex()
{
return &m_mutex;
}


class Block
{
private:
Mutex* m_mutex;
pthread_cond_t m_cond;
string m_message;

public:
Block();
Block(const string& message);
void start();
void stop();
virtual ~Block();




};


Block::Block()
{
cout<<"Block"<<endl;
m_mutex=new Mutex(0);
pthread_cond_init(&m_cond,NULL);
m_message = "";
}


Block::Block(const string& message)
{
cout<<"Block"<<endl;
m_mutex = new Mutex(0);
pthread_cond_init(&m_cond,NULL);
m_message = message;
}


Block::~Block()
{
cout<<"~Block"<<endl;
pthread_cond_destroy(&m_cond);
if(m_mutex != NULL)
{
delete m_mutex;
}


}


void Block::start()
{
m_mutex->lock();
if(!m_message.empty())
cout<<m_message<<endl;
pthread_cond_wait(&m_cond,m_mutex->getMutex());
m_mutex->unlock();
}


void Block::stop()
{
m_mutex->lock();
int a=pthread_cond_signal(&m_cond);
m_mutex->unlock();
}




void* threadOne(void* p)
{
pthread_detach(pthread_self());
cout<<"start blocking"<<endl;

((Block*)p)->start();
cout<<"go out blocking"<<endl;


return NULL;
}


void* threadTwo(void* p)
{
pthread_detach(pthread_self());
sleep(1);
((Block*)p)->stop();


return NULL;
}


int main()
{
Block* block = new Block("Test");
pthread_t tid;


try{
if(0!=pthread_create(&tid,NULL,threadOne,block))
{
throw 0;
}
if(0!=pthread_create(&tid,NULL,threadTwo,block))
{
throw 0;
}

}
catch(int a)
{
cout<<"throw: "<<a<<endl;
}
sleep(5);
delete block;
return 0;

}

现象是:线程one会输出start blocking然后阻塞,之后线程two执行后,线程one会被唤醒继续执行输出go out blocking

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值