全局变量在多线程中的使用

#include <pthread.h>
#include <stdio.h>

 

#define  FAILURE  0
#define  SUCCESS  1
#define  UNS32  unsigned int
#define m_ERROR(format, args...)   printf(format, ## args);//fflush(stdout);

 

static pthread_t   g_pthread_wait;
static pthread_t   g_pthread_signal;
static pthread_t   g_pthread_mt;
pthread_mutex_t         g_pthread_mutex;
pthread_cond_t          g_pthread_cond;

 

static int STATE = 0;

 

UNS32 pthread_initialize_cond(void){
    if ( (pthread_cond_init(&g_pthread_cond, NULL)) != 0 ) {
            m_ERROR("/t!!! ERROR : pthread_cond_init !!!/n");
            return FAILURE;
    } 
    return SUCCESS;
}

 

UNS32 pthread_initialize_mutex(void){
     if ( (pthread_mutex_init(&g_pthread_mutex, NULL)) != 0 ) {
           m_ERROR("/t!!! ERROR : pthread_mutex_init !!!/n");
           return FAILURE;
     } 
     return SUCCESS;
}

 

void pthread_wait(void *args){
     pthread_detach(pthread_self());
     pthread_mutex_lock(&g_pthread_mutex);
 
     pthread_cond_wait(&g_pthread_cond, &g_pthread_mutex);
     STATE = 1;
 
     pthread_mutex_unlock(&g_pthread_mutex);

     pthread_exit(NULL);
}

void pthread_signal(void *args){
      pthread_detach(pthread_self());

      pthread_mutex_lock(&g_pthread_mutex);
      pthread_cond_signal(&g_pthread_cond);
      pthread_mutex_unlock(&g_pthread_mutex);
 
      while(STATE == 0)
               ;
       printf("STATE EXIT!!!/n");
 
       pthread_exit(NULL);
}

int main() {
       pthread_initialize_cond();
       pthread_initialize_mutex();

//线程1 
       if (pthread_create(&g_pthread_wait , NULL, (void * (*)(void *)) pthread_wait, NULL) !=0) {
              return FAILURE;
       }
 

//线程2
      if (pthread_create(&g_pthread_signal , NULL, (void * (*)(void *)) pthread_signal, NULL) !=0) {
              return FAILURE;
      }
 
      printf("while!/n");
      while(1);
}

输出结果为:

while!
STATE EXIT!!!

 

分析:线程1在收到g_pthread_cond条件后,将STATE值赋为1,线程2在跳出while(STATE == 0)循环,打印STATE EXIT!!!

 

补充:

如果将原来的pthread_wait和pthread_signal换成如下的函数:

void pthread_wait(void *args){
        pthread_detach(pthread_self());
        pthread_mutex_lock(&g_pthread_mutex);
        pthread_exit(NULL);
}

void pthread_signal(void *args){
        pthread_detach(pthread_self());

        pthread_mutex_unlock(&g_pthread_mutex);
        pthread_mutex_lock(&g_pthread_mutex);
        printf("sunhao success!!!/n");
        pthread_exit(NULL);
}

打印结果为:

while!
sunhao success!!!
说明锁可以在一个线程中加锁,而在另一个线程中进行解锁。

(如果将绿色的注释去掉的话, 那么就打印不出sunhao success!!!)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值