今天看到了线程那部分, 主要是信号量和互斥量的使用
下面两个程序功能都是统计输入字符串字符数量, 分别用了信号量和互斥量来实现
//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库)