C 语言多线程怎么读文件高效

C 语言多线程怎么读文件高效,第1张

C语言---多个线程读取文件,其代码如下:

#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

}

帮你修改了一下,编译运行没问题,修改的地方都标出来了,

由于不知道你程序的功能,所以没有对你的程序逻辑进行分析

#include <stdio.h>

#include<pthread.h>

#include<semaphore.h>

#include<unistd.h>

//----------------以下是修改的部分

sem_t in

sem_t out

sem_t handout

sem_t handin

sem_t goout

//----------------

int counter=0

void * studentIn(void *a)

{

sem_wait(&in)//修改

counter++

printf("%d\n",counter)

if(counter==30)

{

sem_post(&handout)//修改

return NULL

}

sem_post(&in)//修改

return NULL

}

void * fteacherhandout(void *b)

{

sem_wait(&handout)//修改

printf("teacher said:hand out over\n")

sem_post(&handin)//修改

return NULL

}

void * studentout(void *c)

{

sem_wait(&handin)//修改

sem_wait(&out)//修改

counter--

printf("%d\n",counter)

if(counter==0)

{

sem_post(&goout)//修改

return NULL

}

sem_post(&out)//修改

}

void * fteacherout(void *d)

{

sem_wait(&goout)//修改

printf("teacher go out")

return NULL

}

void main()

{

int i=0

//----------------以下是修改的部分

sem_init(&in,0,1)

sem_init(&out,0,1)

sem_init(&handin,0,0)

sem_init(&handout,0,0)

sem_init(&goout,0,0)

//----------------

pthread_t thread1[30],thread2[30],teacher1,teacher2

pthread_attr_t attr

pthread_attr_init(&attr)

for(i=0i<30i++)

{

pthread_create(&thread1[i],&attr,studentIn,NULL)

}

for(i=0i<30i++)

{

pthread_create(&thread2[i],&attr,studentout,NULL)

}

pthread_create(&teacher1,&attr,fteacherhandout,NULL)

pthread_create(&teacher2,&attr,fteacherout,NULL)

return

}


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/305645.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-27
下一篇2023-04-27

发表评论

登录后才能评论

评论列表(0条)

    保存