多线程信号量程序输出结果为什么不一样。。。
我写了一个关于控制信号量的程序,用来输出某个文件夹下所有符合条件的文件。但是每次由于参数选择的不同输出的文件名都不同,谁知道为什么????
./a.out lili 3(随着这里输入的不同输出的文件数量不一样) (Filename)
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/stat.h>
#include<pthread.h>
#include<limits.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<fnmatch.h>
#include<stddef.h>
#include<dirent.h>
#include<pthread.h>
#define ARGMAX sysconf(_SC_ARG_MAX)
#define LINEMAX sysconf(_SC_LINE_MAX)
#define ARG 1024
typedef struct {
int s;
pthread_mutex_t m;
pthread_cond_t c;
}SEM;
SEM *sem_init(int n){
SEM *s;
s=(SEM*)malloc(sizeof(SEM));
if(s==NULL){
perror("malloc");
exit(EXIT_FAILURE);
}
pthread_mutex_init(&s->m,NULL);
pthread_cond_init(&s->c,NULL);
s->s=n;
return s;
}
void p(SEM*s){
pthread_mutex_lock(&s->m);
while(s->s<1){
pthread_cond_wait(&s->c,&s->m);
}
s->s--;
pthread_mutex_unlock(&s->m);
}
void v(SEM*s){
pthread_mutex_lock(&s->m);
s->s++;
pthread_cond_broadcast(&s->c);
pthread_mutex_unlock(&s->m);
}
static int crawl_thread(char *,int,char *);
static void *grep_thread(void *);
static SEM *sem_full;
static SEM *sem_free;
static pthread_mutex_t lock;
int main(int argc,char *argv[]){
int max_grep_thread;
if(argc!=4) {
printf("Usage:./palim <string> <max-grep-threads> <trees...>\n");
}
else {
max_grep_thread=atoi(argv[2]);
if((strlen(argv[1])<=LINEMAX)&&(strlen(argv[2])<=ARGMAX)){
crawl_thread(argv[1],max_grep_thread,argv[3]);
}
}
return 0;
}
int crawl_thread(char *string,int thread_num,char *pathname){
struct dirent *next;
DIR *dir;
int i;
pthread_attr_t *attr=NULL;
pthread_t tid[thread_num];
sem_full=sem_init(0);
sem_free=sem_init(thread_num);
pthread_mutex_init(&lock,NULL);
if((dir=opendir(pathname))==NULL){
perror("opendir");
// exit(EXIT_FAILURE);
}
else {
char str[ARG];
while((next=readdir(dir))!=NULL){
struct stat sb;
if((strcmp(next->d_name,".")==0)||(strcmp(next->d_name,"..")==0)){
continue;
}
strcpy(str,pathname);
strcat(str,"/");
strcat(str,next->d_name);
if(stat(str,&sb)==-1){
perror("stat");
// exit(EXIT_FAILURE);
}
else {
for(i=0;i<thread_num-1;i++){
if(S_ISREG(sb.st_mode)){
pthread_create(&tid[i],attr,grep_thread,(void*)str);
p(sem_free);
printf("1\n");
v(sem_full);
}
else if(S_ISDIR(sb.st_mode)){
crawl_thread(string,thread_num,str);
}
else continue;
}
}
}
}
closedir(dir);
return 0;
}
void *grep_thread(void *filename){
p(sem_full);
pthread_mutex_lock(&lock);
printf("%s\n",filename);
printf("2\n");
pthread_mutex_unlock(&lock);
v(sem_free);
}