Click here to Skip to main content
15,559,275 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
How do i implement a c program that is able to read from multiple files using multithreading and locks 


What I have tried:

I have avctually not been able to start becuase i don't know how to start.. I need help
Posted
Updated 29-Oct-22 15:06pm

Start by writing the code to process a single file, and try to make it as re-entrant as possible. Once you have that working then you can think about adding threads to process multiple files.
 
Share this answer
 
When you create a thread, you get to pass it a pointer argument. Make that argument a pointer to a struct that contains the path to the file to read.

If all you're doing is reading, and not writing, you shouldn't need locks. When something is read-only, it can have multiple readers. But when it is read-write, it can only have one writer and no readers. A basic lock doesn't support multiple readers, so you need a semaphore. See here[^].
 
Share this answer
 
Quote:
How do i implement a c program that is able to read from multiple files using multithreading and locks

Since Linux does not support threads directly, it is necessary to use the Posix library. It should be noted that all threads are terminated when the main thread is terminated. The threads can then be created with pthread_create(). To prevent the main thread from terminating prematurely, the pthread_join() function can be used to wait until all threads have terminated. The <pthread.h> header and the -lpthreads compiler option must be used.

File locks are used for mutual exclusion when a file is to be read and written by multiple processes, but if I interpret the heading correctly, different files are to be read here with multithreading. Locks would not be necessary for this.

Note: The Linux implementation of mandatory locking is unreliable. The Advisory Locking alternative requires cooperation between the processes involved.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900