Thread: Protected Threads or Semaphores

  1. #1
    Registered User
    Join Date
    Oct 2004

    Protected Threads or Semaphores

    Hi all,

    First of all let me state that im coding on a windows XP platform. I have a function that called logs that writes the state of my program to c:/log.txt, however I want this function to be mutally exclusive so it can only be wrote by one thread at a time. Do you recommend using semaphores or protecting the log function? Also what headers would I hafe to include to achieve this (remembering its for windows)?

    Thanks a lot

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    usually a CRITICAL_SECTION is fine for this.
    for windows windows.h covers most things. make sure you use a multithreaded version of the runtime.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :-

  3. #3
    Registered User
    Join Date
    Jun 2005
    Assuming you only have one program withg multiple threads that need to write to the file, a critical section is fine (and has lower overhead than other schemes, such as semaphores and mutexes).

    If you have multiple programs running (or multiple instances of the same program), the technique will be to open the file for exclusive access when you need to write to it, append whatever you wish to the end, and then close it. This technique will also work with multiple threads in a program, but involves more overhead than simply keeping the file open for writing continually. It is probably applicable if writing to the log file does not occur too often and does not take too long.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Semaphores and threads
    By komalwaseem in forum Linux Programming
    Replies: 6
    Last Post: 04-28-2009, 06:40 AM
  2. Replies: 5
    Last Post: 10-17-2008, 11:28 AM
  3. threads and semaphores
    By jas_atwal in forum Linux Programming
    Replies: 1
    Last Post: 12-25-2007, 07:33 PM
  4. Semaphores Problems
    By mhelal in forum Linux Programming
    Replies: 2
    Last Post: 05-06-2007, 10:36 PM
  5. Threads, Linked Lists, Semaphores, Critical Section ...
    By _jr in forum Windows Programming
    Replies: 4
    Last Post: 06-21-2006, 08:14 AM