POSI threads eplained part 3分析和总结分析和总结.docxVIP

  • 0
  • 0
  • 约1.94万字
  • 约 12页
  • 2023-04-25 发布于上海
  • 举报

POSI threads eplained part 3分析和总结分析和总结.docx

Disclaimer : Disclaimer : The original version of this article was first published on IBM developerWorks, and is property of Westtech Information Services. This document is an updated version of the original article, and contains various improvements made by the Gentoo Linux Documentation team. This document is not actively maintained. POSIX threads explained, part 3 Content: Improve efficiency with condition variables Condition variables explained I ended my previous article by describing a particular dilemma how does a thread deal with a situation where it is waiting for a specific condition to become true? It could repeatedly lock and unlock a mutex, each time checking a shared data structure for a certain value. But this is a waste of time and resources, and this form of busy polling is extremely inefficient. The best way to do this is to use the pthread_cond_wait() call to wait on a particular condition to become true. Its important to understand what pthread_cond_wait() does -- its the heart of the POSIX threads signalling system, and also the hardest part to understand. First, lets consider a scenario where a thread has locked a mutex, in order to take a look at a linked list, and the list happens to be empty. This particular thread cant do anything -- its designed to remove a node from the list, and there are no nodes available. So, this is what it does. While still holding the mutex lock, our thread will call pthread_cond_wait(mycond,mymutex). The pthread_cond_wait() call is rather complex, so well step through each of its operations one at a time. The first thing pthread_cond_wait() does is simultaneously unlock the mutex mymutex (so that other threads can modify the linked list) and wait on the condition mycond (so that pthread_cond_wait() will wake up when it is signalled by another thread). Now that the mutex is unlocked, other threads can access and modify the linked list, possibly adding items. At this point, the pthread_cond_wait() call has not yet

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档