sem&&mutex

    今天看到了线程那部分, 主要是信号量和互斥量的使用

    下面两个程序功能都是统计输入字符串字符数量, 分别用了信号量和互斥量来实现


//syn1.c, 用信号量来实现的
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <string.h>

#define tot 1024
char str[tot];
int time_to_exit=0;
sem_t sem;
sem_t ssem;

void *fun(void *arg){
  int i;
  while (1){
    sem_wait(&sem);
    if (strncmp(str,"end",3)==0){
       time_to_exit=1;
       printf("Thank you!\n");
       sem_post(&ssem); 
       pthread_exit(NULL);
    }
    for (i=0;str[i];i++);
    printf("total charaters: %d\n",i-1);
    sem_post(&ssem); 
  }
}

int main(){  
  pthread_t th;
  int res;

  sem_init(&sem,0,0);
  sem_init(&ssem,0,0);
  res=pthread_create(&th,NULL,fun,NULL);
  if (res!=0){
    perror(NULL);
    return 1;
  }
  while (!time_to_exit){
    fgets(str,tot,stdin);
    sem_post(&sem);
    sem_wait(&ssem);
  }
  sem_destroy(&sem);
  return 0;
}



//syn2.c 用互斥量实现的
#include <stdio.h>
#include <pthread.h>
#include <string.h>

#define tot 1024
char str[tot];
int time_to_exit=0;
pthread_mutex_t mutex;

void *fun(void *arg){
  int i;
  while (1){
    pthread_mutex_lock(&mutex); 
    if (strncmp(str,"end",3)==0){
       time_to_exit=1;
       printf("Thank you!\n");
       pthread_mutex_unlock(&mutex); 
       pthread_exit(NULL);
    }
    for (i=0;str[i];i++);
    printf("total charaters: %d\n",i-1);
    str[0]=0;
    pthread_mutex_unlock(&mutex); 
  }
}

int main(){  
  pthread_t th;
  int res;
  
  res=pthread_mutex_init(&mutex,NULL);
  if (res!=0){
    perror(NULL);
    return 1;
  }
  res=pthread_create(&th,NULL,fun,NULL);
  if (res!=0){
    perror(NULL);
    return 1;
  }
  while (!time_to_exit){
    if (str[0]==0){
      pthread_mutex_lock(&mutex); 
      fgets(str,tot,stdin);
      pthread_mutex_unlock(&mutex); 
    }
  }
  return 0;
}

运行结果如下(注意编译时, 要定义D_REENTRANT宏和加入pthread库)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值