线程编程之:加锁解锁最简单例子

来源:互联网 发布:jsp获取客户端mac地址 编辑:程序博客网 时间:2024/05/20 18:03
//  pthread_mutex_t BackUpKey;                           main头上应该定义该变量
//    pthread_mutex_init(&BackUpKey,NULL);           main在最前应该申请该资源
//    pthread_mutex_destroy(&BackUpKey);               main在最后应该销毁掉该资源
//  extern pthread_mutex_t BackUpKey;               在外部引用该对象
//  在具体方法中使用:pthread_mutex_lock(&BackUpKey);加锁

//         pthread_mutex_unlock(&BackUpKey);解锁       ===》 #include <pthread.h>



通过以上东东,就可以实现一个简单的线程互斥程序罗。


包含在类内的锁对象,应该如此使用:加上类的限定符号。(在类内部是如此使用的。)

class RChat
{
public:
static pthread_mutex_t RChatKey;  //   写成static是非常有必要的,则表示全局唯一麻,并不是每个RChat对象都有自己的单独的锁,那就不行了,对吧!

          .........

}

main.cpp:

extern pthread_mutex_t RChat::RChatKey;                              //注意:这里就要加上类域限定符RChat:: 
extern pthread_mutex_t RChatIndex::RChatIndexKey;

main(){

pthread_mutex_init(&RChat::RChatKey,NULL);        //同上


pthread_mutex_destroy(&RChat::RChatKey);  //同上

}









原创粉丝点击