Assignning same char value on same location from multiple threads

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jose Ortiz

    Assignning same char value on same location from multiple threads

    Each thread executes:
    my_char_array[i] = 1;

    my_char_array is shared. Char i is private to each thread. However, the value of i may be the same for two or more threads.

    No reading is performed. Reading of my_char_array will be done after all threads are finished.

    Should I worry and place a mutex lock?

    In other words, would it a problem if two threads try to execute say

    my_char_array[5]=1

    would result in a value different than 1 being set.
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    #2
    Anytime a global resource is accessed by more than one thread the resource should have a Mutex associated with it.

    POSIX Pthread libraries on Linux. YoLinux: Linux Information Portal includes informative tutorials and links to many Linux sites.

    Comment

    • non mouse

      #3
      If they are all writing the same '1' to it, it should be fine. I am assuming it is an array of 'int's also. This is dodgy programming. If you are doing anything other than this, it is *extremely* dodgy programming.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Please elaborate on what you're trying to do. What is the meaning of the my_char_array? Do the threads ever write anything other than 1 into the array?

        Do you intend to use my_char_array as a mutual-exclusion lock? There are reliable algorithms for implementing mutual-exclusion via shared memory without any OS-provided mutex support. See Dekker's algorithm, Peterson's algorithm, and Lamport's bakery algorithm. Notice that these algorithms are all versions of spinlocks.

        By the way, it is imperative for all variables accessed by multiple threads to be declared as volatile.

        Comment

        • Jose Ortiz

          #5
          Thank you for your replies.

          Array my_char_array[] is an array of char initialized to zeros. The only value to be set by the threads is 1. I do want to avoid using mutex variables.

          I'm working on the LU factorization of large sparse matrices. Each thread works with a set of rows. While working a row, a thread tags only a subset of the columns. The issue is that multiple threads may tag the same column. When all threads are finished, I need to know which columns were tagged. Array my_char_array should tell me so.

          Comment

          Working...