下面一个例子说明了信号量的用法 信号量往往用于两个进程或线程的同步,使得他们能够和谐的工作 这个例子创建了四个线程,两个用于读取文件中的数据,两个用于把读取到的数据进行相应的处理 一个把这些数据进行和运算,一个用于乘法运算 #include <stdio.h> #include <semaphore.h> #include <pthread.h> #define MAX 100 int buf[MAX][2]; sem_t sem; int size=0; //read data from 1.dat void read_data1(void) { FILE *fp=fopen("1.dat","r"); while(!feof(fp)) { fscanf(fp,"%d %d",&buf[size][0],&buf[size][1]); sem_post(&sem); ++size; } fclose(fp); } //read data from 2.dat void read_data2(void) { FILE *fp=fopen("2.dat","r"); while(!feof(fp)) { fscanf(fp,"%d %d",&buf[size][0],&buf[size][1]); sem_post(&sem); ++size; } fclose(fp); } //do the first kind of things on these datas void handle_first(void) { while(1) { sem_wait(&sem); printf("The result of the expression:%d+%d is %d/n", buf[size][0],buf[size][1],buf[size][0]+buf[size][1]); --size; } } //do the second king of things on these datas void handle_second(void) { while(1) { sem_wait(&sem); printf("The result of the expression:%d*%d is %d/n", buf[size][0],buf[size][1],buf[size][0]*buf[size][1]); --size; } } int main() { pthread_t pt1,pt2,pt3,pt4; sem_init(&sem,0,0); pthread_create(&pt1,NULL,(void*)read_data1,NULL); pthread_create(&pt2,NULL,(void*)read_data2,NULL); //the timeshot for this program is too long //only one thread can get all the buf data //and then the other thread can't get any data //so it looks like that it doesn't execute. pthread_create(&pt3,NULL,(void*)handle_first,NULL); pthread_create(&pt4,NULL,(void*)handle_second,NULL); //in case of exit so early that let it wait here //pthread_join(pt3,NULL); } linux信号量机制 linux信号量机制的相关用法及其简单例子