linux怎么调用封装,用c++封装linux系统调用

#include #include#include#include

using namespacestd;classRWLock {private:

pthread_mutex_t cnt_mutex;

pthread_cond_t rw_cond;intrd_cnt, wr_cnt;

RWLock(const RWLock&);

RWLock& operator= (const RWLock&);public:

RWLock(): rd_cnt(0),wr_cnt(0)

{

pthread_mutex_init(&cnt_mutex, NULL);

pthread_cond_init(&rw_cond, NULL);

}voidget_shared_lock()

{

pthread_mutex_lock(&cnt_mutex);while (wr_cnt >0)

{

pthread_cond_wait(&rw_cond,&cnt_mutex);

}

rd_cnt++;

pthread_mutex_unlock(&cnt_mutex);

}voidrelease_shared_lock()

{

pthread_mutex_lock(&cnt_mutex);

rd_cnt--;if (0 ==rd_cnt)

{

pthread_cond_signal(&rw_cond);

}

pthread_mutex_unlock(&cnt_mutex);

}voidget_exclusive_lock()

{

pthread_mutex_lock(&cnt_mutex);while (rd_cnt+wr_cnt>0)

{

pthread_cond_wait(&rw_cond,&cnt_mutex);

}

wr_cnt++;

pthread_mutex_unlock(&cnt_mutex);

}voidrelease_exclusive_lock()

{

pthread_mutex_lock(&cnt_mutex);

wr_cnt--;

pthread_cond_broadcast(&rw_cond);

pthread_mutex_unlock(&cnt_mutex);

}~RWLock()

{

pthread_mutex_destroy(&cnt_mutex);

pthread_cond_destroy(&rw_cond);

}

};classTest

{private:

RWLocklock;static void* shared_task_handler(void*arg)

{

Test* testptr = static_cast(arg);

testptr->lock.get_shared_lock();//得到共享锁//do the shared task here

testptr->lock.release_shared_lock();

}static void * exclusive_task_handler(void *arg)

{

Test* testptr = static_cast(arg);

testptr->lock.get_exclusive_lock();//do the exclusive task here

testptr->lock.release_exclusive_lock();

}public:

typedefvoid* (*ThreadFunc) (void*);voidstart()

{

srand(time(NULL));const int THREADS_NO=rand()%100;

pthread_t* threads = newpthread_t[THREADS_NO];for(int i=0; i

{

ThreadFunc tmpfunc= rand()%2?shared_task_handler : exclusive_task_handler;if (pthread_create(threads+i,NULL,tmpfunc,this))

{

cerr<< "pthread_create fails" <

exit(1);

}

}for(int i=0; i

{

pthread_join(threads[i],NULL);

}

delete[] threads;

}

};intmain()

{

Test tmptest;

tmptest.start();

}

static_cast< type-id >( expression )inti;float f = 166.71;

i= static_cast(f);

此时结果,i的值为166。

cstdlib是C++里面的一个常用函数库, 等价于C中的//blog.chinaunix.net/uid-52437-id-2108727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值