pthread_mutex_init

This is a discussion on pthread_mutex_init within the C Programming forums, part of the General Programming Boards category; I'm trying to find out if there is a way to init a pthread_mutex so that he starts locked. With ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    101

    Question pthread_mutex_init

    I'm trying to find out if there is a way to init a pthread_mutex so that he starts locked.

    With pthread_mutex_init() it starts unlocked by default and I don't know how to change that.

    Any suggestions?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    395
    why not call pthread_mutex_lock() after pthread_mutex_init(), this is not atomic but as you're in the initialization phase, only one thread/process is doing it, right? this is done once

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    101
    I thought of that but isn't that bad programming?

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,630
    Not in of itself. In fact, that's your only option.

    The next question is "why?".

    gg

  5. #5
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,230
    Quote Originally Posted by kotoko View Post
    I thought of that but isn't that bad programming?
    No, it's fine. There is a macro, PTHREAD_MUTEX_INITIALIZER, which you can use to statically initialize a mutex, but it initializes it to an unlocked state. There is no initializer macro which initializes to a locked state.

    I sort of wonder why the mutex should begin its life in a locked state...
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    101
    The question really was why was I doing it.

    It turns out I should use a posix semaphore instead.

    Thanks for all the help anyway.

Popular pages Recent additions subscribe to a feed

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21