Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <string.h>
- typedef struct{
- char filename[128];
- char target[25];
- int idThread;
- } Param_thread;
- //prototype
- void *fctThread(void* param);
- pthread_t thread_handle[4];
- int main(int argc, char** argv)
- {
- int i=0, *retThread[4];
- int ret[4];
- Param_thread param[4];
- //initionalisation param
- strcpy(param[0].filename,"lorem.txt");
- strcpy(param[0].target,"lor");
- param[0].idThread = i;
- strcpy(param[1].filename,"lorem.txt");
- strcpy(param[1].target,"lor");
- param[1].idThread = 1;
- strcpy(param[2].filename,"lorem.txt");
- strcpy(param[2].target,"lor");
- param[2].idThread = 2;
- strcpy(param[3].filename,"lorem.txt");
- strcpy(param[3].target,"lor");
- param[3].idThread = 3;
- printf("Lancement des thread secondaires\n");
- for ( i = 0; i < 4; ++i)
- {
- printf("lancement thread %d\n",i);
- ret[i] = pthread_create(&thread_handle[i], NULL, (void*(*)(void*))fctThread, (void*)¶m[i]);
- }
- for ( i = 0; i < 4; ++i)
- {
- printf("join thread %d\n",i);
- ret[i] = pthread_join(thread_handle[i], (void**) &retThread[i]);
- printf("valeur renvoyée par le thread %d : %d\n",i,*retThread[i]);
- }
- printf("fin principale\n");
- }
- void* fctThread(void *param){
- int nbrOcc = 0,nbr_read=1;
- int hd,i=0,j=0;
- Param_thread *arg = (Param_thread*) malloc(sizeof(Param_thread));
- arg = (Param_thread*) param;
- char output[50];
- printf("filename : %s\n",arg->filename);
- printf("cible : %s\n",arg->target);
- printf("idThread : %d\n",arg->idThread);
- char buffer[4];
- while(nbr_read>0){
- if( (hd = open(arg->filename,O_RDONLY)) == -1 ) {
- perror("erreur ouverture fichier");
- exit(0);
- }
- sprintf(output, "%%%ds\n",arg->idThread*5);
- printf(output,"*");
- if( (lseek(hd,i,SEEK_SET)) == -1 ){
- perror("erreur lseek");
- exit(0);
- }
- if ( (nbr_read = read(hd,buffer,3)) < 0){
- printf("fin de fichier\n");
- break;
- }
- if( (close(hd)) == -1){
- perror("erreur close");
- }
- // printf("%s-%s\n",buffer,arg->target);
- if(strcmp(buffer,arg->target) == 0){
- nbrOcc++;
- }
- i++;
- }
- free(arg);
- pthread_exit(&nbrOcc);
- }
Advertisement
Add Comment
Please, Sign In to add comment