Can using sem_trywait()
let you get into a deadlock or livelock?
Asked
Active
Viewed 847 times
0

Bill the Lizard
- 398,270
- 210
- 566
- 880

user1422508
- 99
- 1
- 2
- 6
2 Answers
0
If you have multiple threads, nearly any function can participate in a potential livelock or deadlock (or both), depending on how it's used. The algorithm matters. Now, there are certain specific patterns of use of sem_trywait
that may or may not be liable to form a live or deadlock, but from just the function name, it's hard to answer with any specificity.

bdonlan
- 224,562
- 31
- 268
- 324
-
The function itself cannot deadlock because it does not wait for anything, but of course calling it in a loop can deadlock. – R.. GitHub STOP HELPING ICE Jul 12 '12 at 03:11
-
@R., you don't even need a loop - just interaction with another, non-trywait lock can do it. My point is, you can't declare a program free of dead/livelocks just because it uses sem_trywait – bdonlan Jul 12 '12 at 03:22
-
A program that doesn't loop (or recurse) can't deadlock because each instruction makes forward progress... :-) – R.. GitHub STOP HELPING ICE Jul 12 '12 at 03:50
-
@R., true, such a program would be an example of a deadlock (and livelock!) free use of whatever it happens to be using (assuming it doesn't make use of other blocking calls either). My point is just that, the information "it uses sem_trylock" is insufficient to determine whether the program (or locking protocol, etc) is livelock or deadlock-free. – bdonlan Jul 12 '12 at 03:55
0
It should fail with E_DEADLK if two threads are contending for the same resource locked by each other's semaphore. This is correct behaviour but you need to detect it and retry if it happens. In other words, yes, it can deadlock, but the system will detect this and fail out of the function rather than leave you hanging.

David G
- 5,408
- 1
- 23
- 19