Please use thread to complete the following program: one process opens a file data.txt, then creates a thread my_thread. The job of the thread my_thread is to count how many lines exist in the file data.txt, and return the number of lines to the calling process. The process then prints this number to the screen.
Basically, you need to implement main_process.c and thread_function.c.
Basic structure of main_process.c:
int main ()
{
Open the file data.txt and obtain the file handler fh;
Create a thread my_thread using pthread_create; pass fh to my_thread;
Wait until my_thread terminates, using pthread_join;
Print out how many lines exist in data.txt.}
Basic structure of thread_function.c:
void *count_lines(void *arg)
{
Obtain fh from arg;
Count how many lines num_lines exist in fh;
Close fh;
Return num_lines
}

Respuesta :

Answer:

Here is the code:-

//include the required header files

#include<stdio.h>

#include<pthread.h>

// method protocol definition

void *count_lines(void *arg);

int main()

{

    // Create a thread handler

    pthread_t my_thread;

    // Create a file handler

    FILE *fh;

    // declare the variable

    int *linecnt;

    // open the data file

    fh=fopen("data.txt","r");

// Create a thread using pthread_create; pass fh to my_thread;

    pthread_create(&my_thread, NULL, count_lines, (void*)fh);

    //Use pthread_join to terminate the thread my_thread

    pthread_join( my_thread, (void**)&linecnt );

    // print the number of lines

printf("\nNumber of lines in the given file: %d \n\n", linecnt);

    return (0);

}

// Method to count the number of lines

void *count_lines(void *arg)

{

    // variable declaration and initialization

    int linecnt=-1;

    char TTline[1600];

    //code to count the number of lines

    while(!feof(arg))

    {

         fgets(TTline,1600,arg);

         linecnt++;

    }

    pthread_exit((void *)linecnt);

    // close the file handler

    fclose(arg);

}

Explanation:

Program:-

Ver imagen tallinn