अंतर को समझने का सबसे अच्छा तरीका उदाहरण की मदद से है। नीचे सेमफोर के माध्यम से शास्त्रीय निर्माता उपभोक्ता समस्या को हल करने का कार्यक्रम है। पारस्परिक बहिष्कार प्रदान करने के लिए हम सामान्य रूप से एक बाइनरी सेमफोर या म्यूटेक्स का उपयोग करते हैं और सिंक्रनाइज़ेशन प्रदान करते हैं गिनती सेमफोर का उपयोग करें। (विभिन्न धागा बीच साझा संसाधन के लिए उपयोग करने के लिए aribtrate)
BufferSize = 3;
semaphore mutex = 1; // used for mutual exclusion
semaphore empty = BufferSize; // used for synchronization
semaphore full = 0; // used for synchronization
Producer()
{
int widget;
while (TRUE) { // loop forever
make_new(widget); // create a new widget to put in the buffer
down(&empty); // decrement the empty semaphore
down(&mutex); // enter critical section
put_item(widget); // put widget in buffer
up(&mutex); // leave critical section
up(&full); // increment the full semaphore
}
}
Consumer()
{
int widget;
while (TRUE) { // loop forever
down(&full); // decrement the full semaphore
down(&mutex); // enter critical section
remove_item(widget); // take a widget from the buffer
up(&mutex); // leave critical section
consume_item(widget); // consume the item
}
}
उपरोक्त कोड में म्युटेक्स चर पारस्परिक अपवर्जन (केवल एक धागा महत्वपूर्ण अनुभाग का उपयोग करने की अनुमति देते हैं) जबकि पूर्ण और खाली चर प्रदान करता है synchonization के लिए उपयोग किया जाता है।