我们已经用信号量来实现线程间的互斥,达到了互斥锁的效果,今天这篇文章将讲述怎样用信号量去实现同步。
         信号量的互斥同步都是通过PV原语来操作的,我们可以通过注册两个信号量,让它们在互斥的问题上互动,从而达到同步。通过下面实例就可以很容易理解:
 
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <semaphore.h>
 
#define return_if_fail(p) \
          if(!p) { printf("[%s]:func error!", __func__); return; }
 
typedef struct _PrivInfo {
          sem_t sem1;
          sem_t sem2;
          int lock_var;
          time_t end_time;
}PrivInfo;
 
void  info_init(PrivInfo *thiz);
void  info_destroy(PrivInfo *thiz);
void *pthread_function1(void *paramthiz);
void *pthread_function2(void *paramthiz);

int main (int argc, char** argv) {
          pthread_t pt_1 = 0;
          pthread_t pt_2 = 0;
          int ret = 0;
          PrivInfo *thiz = NULL;
          thiz = (PrivInfo*)malloc(sizeof(PrivInfo));
          if(NULL == thiz) {
                    return -1;
          }
          info_init(thiz);
          ret = pthread_create(&pt_1, NULL, pthread_function1, (void*)thiz);
          if(0 != ret) {
                    perror("pthread1 creation failed!"); 
          }
 
          ret = pthread_create(&pt_2, NULL, pthread_function2,(void*)thiz);
          if(0 != ret) {
                    perror("pthread2 creation failed!"); 
          }
          pthread_join(pt_1, NULL);
          pthread_join(pt_2, NULL);
          info_destroy(thiz);
 
          free(thiz); 
          thiz = NULL;
 
          return 0;
}
 
void info_init(PrivInfo *thiz) {
          return_if_fail(&thiz != NULL);
          thiz->lock_var = 0;
          thiz->end_time = time(NULL) + 10;
          sem_init(&thiz->sem1, 0, 0);
          sem_init(&thiz->sem2, 0, 1);
 
          return;
}
 
void info_destroy(PrivInfo *thiz) {
          return_if_fail(&thiz != NULL);
          sem_destroy(&thiz->sem1);
          sem_destroy(&thiz->sem2);
 
          return;
}
 
void *pthread_function1(void *paramthiz) { 
          int i = 0;
          PrivInfo *thiz = (PrivInfo *)paramthiz;
          while(time(NULL) < thiz->end_time) {
                    sem_wait(&thiz->sem2);
                    printf("thread1 get the lock.\n");
  
                    sem_post(&thiz->sem1);
                    printf("thread1 unlock.\n");
                    sleep(1);
          }
          pthread_exit(NULL);
}
 
void *pthread_function2(void *paramthiz) { 
          PrivInfo *thiz = (PrivInfo *)paramthiz;
          while(time(NULL) < thiz->end_time) {
                    sem_wait(&thiz->sem1);
                    printf("thread2 get the lock. \n");
  
                    sem_post(&thiz->sem2);
                    printf("thread2 unlock.\n");
 
                    sleep(1);
          }
  
          pthread_exit(NULL);
}