看下面例子
#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