2
A
回答
7
如果你說互斥/條件變量是允許的,然後檢查:
#include <pthread.h>
typedef struct
{
unsigned int count;
pthread_mutex_t lock;
pthread_cond_t cond;
} semaph_t;
int
semaph_init (semaph_t *s, unsigned int n)
{
s->count = n;
pthread_mutex_init (&s->lock, 0);
pthread_cond_init (&s->cond, 0);
return 0;
}
int
semaph_post (semaph_t *s)
{
pthread_mutex_lock (&s->lock); // enter monitor
if (s->count == 0)
pthread_cond_signal (&s->cond); // signal condition
++s->count;
pthread_mutex_unlock (&s->lock); // exit monitor
return 0;
}
int
semaph_wait (semaph_t *s)
{
pthread_mutex_lock (&s->lock); // enter monitor
while (s->count == 0)
pthread_cond_wait (&s->cond, &s->lock); // wait for condition
--s->count;
pthread_mutex_unlock (&s->lock); // exit monitor
return 0;
}
0
這是對Wikipedia article regarding monitors的主要答案。
monitor class Semaphore
{
private int s := 0
invariant s >= 0
private Condition sIsPositive /* associated with s > 0 */
public method P()
{
if s = 0 then wait sIsPositive
assert s > 0
s := s - 1
}
public method V()
{
s := s + 1
assert s > 0
signal sIsPositive
}
}
相關問題
- 1. 使用信號量來實現監視器
- 2. 使用監視器概念實現信號量
- 3. 信號量併發性
- 4. 信號量實現:監控與睡眠理髮,巨大的性能差異
- 5. Java監視器實現
- 6. 實現信號量
- 7. 實現信號量
- 8. 在C++中使用互斥信號和條件變量實現監視器
- 9. Java監視器和線程併發性
- 10. 操作發送給監視器的信號
- 11. 在java中實現計數信號量
- 12. IllegalMonitorException在Java中使用信號量和監視器
- 13. Java中的進度監視器實現
- 14. 實現一個隊列的信號量
- 15. 實現沒有信號量的鎖
- 16. 實現不同監視器的顏色一致性
- 17. 發現兩個信號的一致性
- 18. 如何實現分佈式信號量?
- 19. 如何實現Mac OS HTTP監視器
- 20. 等待/信號(信號量)如何實現僞代碼「工作」?
- 21. 如何實現全局信號量類
- 22. 使用java實現計數信號量
- 23. 無法理解或實現信號量
- 24. Django post_save()信號的實現
- 25. 如何使用java信號量來實現這種併發情況?
- 26. 對等網絡鎖定模式(類似於互斥/信號量/監視器)
- 27. 如何在qtcreator中實現Qabstractvideosurface並監視每幀視頻?
- 28. 如何實現監聽器?
- 29. Android Button監聽器實現
- 30. WebView流量監視器
可以使用條件變量嗎? – Karmastan 2011-04-06 01:49:55
@Karmastan:是的。 – 2011-04-06 02:18:57
[監視器上的Wikipedia頁面](http://en.wikipedia.org/wiki/Monitor_%28synchronization%29)包含這樣一個例子。 – caf 2011-04-06 05:41:10