#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
}
解决方法如下:使用同步机制。可以使用提供的信号量机制,或者采用文件锁机制来实现线程间文件的同步处理。这样可以保证每个线程在写入文件前都必须获得特定的信号量或文件锁,从而保证线程的正常执行。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)