Posix线程同步1--互斥量(含代码实例)

互斥量:相当于锁,初始化一个互斥锁后,线程1在取得互斥锁后,在线程1释放这把互斥锁前的这段时间,其它线程(比如线程2)申请互斥锁将会阻塞,一直到线程1释放锁以后,线程2才有可能申请到锁。
应用场合:多线程对同一个全局变量的修改操作上。
主要函数有两个:
1)申请锁
int pthread_mutex_lock(pthread_mutex_t *mutex);
2)释放锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);

 代码实例如下:

/****************************************************************
* 说明: Posix线程同步--互斥量(mutex)实例
         线程1对全局变量g_cnt1递增,
         线程2对全局变量g_cnt1递减,
         线程3对全局变量g_cnt2递增,
         线程4对全局变量g_cnt2递减
         对全局变量操作前后各用一个临时变量保存值,差值不为1说明数据不同步。
         其中线程1,2对全局变量的访问引入mutex同步机制,线程3,4则没有。
* 日期: 2008-3-18 14:19
****************************************************************
*/

#include 
< pthread.h >
#include 
< stdio.h >
#include 
< sys / time.h >
#include 
< string.h >
int  g_cnt1  =   0 ;
int  g_cnt2  =   0 ;
pthread_mutex_t g_mutex 
=  PTHREAD_MUTEX_INITIALIZER; 

void   *  thread1( void   * arg)
{
    printf(
"thread1 begin ");
    
int t1,t2;
    
while(1)
    
{        
        pthread_mutex_lock(
&g_mutex);
        t1 
= g_cnt1;
        sleep(
1);
        g_cnt1
++;
        t2 
= g_cnt1;
        pthread_mutex_unlock(
&g_mutex);
        
if(t2 - t1 != 1)
            printf(
"thread1 t1:%d,t2:%d ",t1,t2);
        
    }

}

void   *  thread2( void   * arg)
{
    printf(
"thread2 begin ");
    
int t1,t2;
    
while(1)
    
{        
        pthread_mutex_lock(
&g_mutex);
        t2 
= g_cnt1;
        sleep(
2);
        g_cnt1
--;
        t1 
= g_cnt1;
        pthread_mutex_unlock(
&g_mutex);
        
if(t2 - t1 != 1)
            printf(
"thread2 t1:%d,t2:%d ",t1,t2);
    }

}

void   *  thread3( void   * arg)
{
    printf(
"thread3 begin ");
    
int t1,t2;
    
while(1)
    
{        
        t1 
= g_cnt2;
        sleep(
1);
        g_cnt2
++;
        t2 
= g_cnt2;
        
if(t2 - t1 != 1)
            printf(
"thread3 t1:%d,t2:%d ",t1,t2);
    }

}

void   *  thread4( void   * arg)
{
    printf(
"thread4 begin ");
    
int t1,t2;
    
while(1)
    
{        
        t2 
= g_cnt2;
        sleep(
2);
        g_cnt2
--;
        t1 
= g_cnt2;
        
if(t2 - t1 != 1)
            printf(
"thread4 t1:%d,t2:%d ",t1,t2);
    }

}

int  main( void )
{
    
int tid1,tid2,tid3,tid4;
    printf(
"main thread begin ");
    pthread_mutex_init(
&g_mutex,NULL);
    pthread_create(
&tid1,NULL,thread1,NULL);
    pthread_create(
&tid2,NULL,thread2,NULL);
    pthread_create(
&tid3,NULL,thread3,NULL);
    pthread_create(
&tid4,NULL,thread4,NULL);
    printf(
"main thread exit ");
    
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值