2

I couldn't find a definitive answer so this is the place.
Windows' EnterCriticalSection acts in the way that I can lock it multiple times in the same thread, and I need to unlock it on the way out the exact number of times so it will get free.

What is the Linux equivalent? Does pthread mutex acts in the same way? Or is it multiple locks, single unlock...

Ajay
  • 18,086
  • 12
  • 59
  • 105
Boaz
  • 4,864
  • 12
  • 50
  • 90
  • posix supports recursive mutexes (single mutex which the same thread can lock/unlock n times). However, IMO the need for this indicates bad design... – Nim Jul 12 '12 at 11:28
  • @Nim: The bad design part depends. I agree that it should be avoided when possible, but sometimes avoiding it leads to having a much worse design ^^ – Andy Jul 12 '12 at 11:34

4 Answers4

3

Use boost::recursive_mutex and you won't have to think about the operating system anymore

Andy
  • 176
  • 1
  • 1
  • 10
  • why using a llibrary like boost when you can use standard libraries ? – A.G. Jul 12 '12 at 11:36
  • well his question is tagged with both windows and linux, so I assumed he's doing a cross platform application anyway – Andy Jul 12 '12 at 11:39
  • so using PTHREAD_MUTEX_RECURSIVE_NP like @A.G. suggested is incorrect? – Boaz Jul 12 '12 at 11:40
  • @Boaz: no it is not incorrect. choose what you prefer. I just suggested boost to you since then you won't have to worry about how x is done in y operating system, and that's what made you ask – Andy Jul 12 '12 at 11:47
  • @alex - thanks for the idea of boost. For now this code is potentially multi-platform, so boost is an overkill at this stage. For now I'd rather use native so PTHREAD_MUTEX_RECURSIVE_NP is preferrable – Boaz Jul 12 '12 at 12:00
2

you can use pthread mutex in recursive mode, using attribute PTHREAD_MUTEX_RECURSIVE_NP.

Linux equivalent is described in this article (see "listing2. Equivalent Linux code")

http://www.ibm.com/developerworks/linux/library/l-ipc2lin3/index.html.

A.G.
  • 1,279
  • 1
  • 11
  • 28
1

Why don't you use the ADONTEC's W2LPL library (http://adontec.com/windows-to-linux-port-library.htm) it offers nearly all you are looking for.

bop1
  • 11
  • 1
-1

You can use a mutex, have look to this http://en.wikipedia.org/wiki/Critical_section

Just make sure you put it into recursive mode.

The following link describes how to do that for pthreads: http://www.ibm.com/developerworks/linux/library/l-ipc2lin3/index.html

sehe
  • 374,641
  • 47
  • 450
  • 633
A.G.
  • 1,279
  • 1
  • 11
  • 28