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

时间:2022-07-02 08:55:46

#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!!!)