#include
#include
#include
#include
#include
#include
#define THREAD_NUM 25
typedef struct
{undefined
FILE *_fp
int _nThreadId//第几个线程
sem_t *_semLock
}IDD_THREAD_PARAM
void *ThreadFunc(void *args)
{undefined
char sLine[100+1]
FILE *fpRead = ((IDD_THREAD_PARAM *)args)->_fp
sem_t *semLock = ((IDD_THREAD_PARAM *)args)->_semLock
int nId = ((IDD_THREAD_PARAM *)args)->_nThreadId
sem_wait(semLock)
while(!feof(fpRead))
{undefined
memset(sLine,0,sizeof(sLine))
fgets(sLine,100,fpRead)
fprintf(stderr,"Thread ID-%d:%s",nId,sLine)
}
sem_post(semLock)
}
int main()
{undefined
pthread_t *pThreads
sem_t semLock
pThreads = (pthread_t *)malloc(THREAD_NUM*sizeof(pthread_t))
sem_init(&semLock,0,1)
FILE *fp = fopen("test.txt","r")
//开始线程循环
IDD_THREAD_PARAM param
for(int i=0i
{undefined
memset(param,0,sizeof(IDD_THREAD_PARAM))
param._fp = fp
param._nThreadId = i
param._semLock = &semLock
pthread_create((pThreads+i),NULL,ThreadFunc,param)
}
for(int i=0i
pthread_join(*(pThreads+i),NULL)
free(pThreads)
pThreads = NULL
fclose(fp)
fp = NULL
return 0
}
线程参数,传地址使用动态分配吧,你只用一个buffer,后面的很可能就把前面的给覆盖了。把所有的输出printf使用一个互斥的信号量同步一下就行了吧,C的标准库不是线程安全的。
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)