Thread: Accessing a file with threads

  1. #1
    Registered User
    Join Date
    Dec 2001

    Accessing a file with threads

    If I were, in the main() function, to open a file, then kickoff a number of threads that would all access the file with each thread reading in a line each using fgets (which says that it is thread safe if I am reading the man page correctly), then each thread will be able to do this without tripping over each other, correct?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    I guess so, if it says that it is thread-safe.

    Though which thread gets which line is probably more interesting...
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2001
    In this case it doesnt matter because each line is a single record, and no two lines are dependant on each other, so each line can be processed independently to any other. I wanted to check that thread safe meant that no two threads could be calling fgets at the same time. I guess that it has some sort of atomic queueing mechanism in there.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    I looked at the source in the MS library a while back, and they have a mutex to prevent more than one thread inside the file function at any time - it is one lock per file, so if you open multiple files, they are not blocking on each other. Of course, I don't know if the C-library is implemented the same way - but I expect that to be the case.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File being filled with NULLs
    By Tigers! in forum Windows Programming
    Replies: 2
    Last Post: 06-30-2009, 05:28 PM
  2. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  3. Making a LIB file from a DEF file for a DLL
    By JMPACS in forum C++ Programming
    Replies: 0
    Last Post: 08-02-2003, 08:19 PM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 AM