473,769 Members | 3,755 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Semaphore or what should I use?

Hi

I´m wondering why there are so few examples with Semaphore.
Is it obsolete?

I´ve got a Class Data.
It offers 2 Threads methods for updating, editing, .. a private
dictionary.

Now I have to make sure, that both threads are synchronal,
1 thread edits something and the other is blocked until the first
thread is ready.

Isn´t it a good idea to do this with a semaphore?

And if I should use a Semaphore here, could anybody give me an example
how it should look like?

Everything that I test throws errors :(

Thank you :)
Bye, Bastian
Jul 18 '05 #1
7 4358
>>>>> "Bastian" == Bastian Hammer <we*******@haus tierworld.de> writes:

Bastian> Now I have to make sure, that both threads are
Bastian> synchronal, 1 thread edits something and the other is
Bastian> blocked until the first thread is ready.

Bastian> Isn´t it a good idea to do this with a semaphore?

Semaphore will do, but this is a classical use case for
threading.Lock.

There should be lots of stuff regarding locks (or more googleably,
"mutexes") on the net.

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #2
Ville Vainio a écrit :
>>"Bastia n" == Bastian Hammer <we*******@haus tierworld.de> writes:

Bastian> Now I have to make sure, that both threads are
Bastian> synchronal, 1 thread edits something and the other is
Bastian> blocked until the first thread is ready.

Bastian> Isn´t it a good idea to do this with a semaphore?

Semaphore will do, but this is a classical use case for
threading.Lock.

There should be lots of stuff regarding locks (or more googleably,
"mutexes") on the net.


I don't agree. Mutexes (or locks) are best suited for critical sections
(ie. sections that cannot be run by many thread at the same time). The
kind of synchonisation Bastian want is not really semaphore either but
more event. This python "Event" object is described in the section 7.5.5
of the documentation of Python 2.3. There is no example, but I think
Event are quite strait forward : you creates it, then some thread block,
waiting the event to occure while some other thread execute until it set
the event, allowing the blocked thread to go on its own execution :)
Here a small working example :

***8<********** **8<*********** ****8<********* *
import threading, time

class MyThread(thread ing.Thread):
def __init__(self):
threading.Threa d.__init__(self )
self._event = threading.Event ()
self._exit = False
def run(self):
while 1:
print "Waiting for an event to continue"
self._event.wai t()
print "Ok, the thread is unblocked now :)"
if self._exit:
return
self._event.cle ar()
def unblock(self):
self._event.set ()
def exit(self):
self._exit = True
self.unblock()

t = MyThread()
t.start()
time.sleep(1)
t.unblock()
time.sleep(1)
t.unblock()
time.sleep(1)
t.exit()
***8<********** **8<*********** ****8<********* *
Pierre
Jul 18 '05 #3
Pierre Barbier de Reuille <pi************ @cirad.fr> writes:
Ville Vainio a écrit :
>>>"Bastia n" == Bastian Hammer <we*******@haus tierworld.de> writes:

Bastian> Now I have to make sure, that both threads are

Bastian> synchronal, 1 thread edits something and the other is
Bastian> blocked until the first thread is ready.
Bastian> Isn´t it a good idea to do this with a semaphore?

Semaphore will do, but this is a classical use case for
threading.Lock.

There should be lots of stuff regarding locks (or more googleably,
"mutexes") on the net.

I don't agree. Mutexes (or locks) are best suited for critical sections (ie.
sections that cannot be run by many thread at the same time).


Please don't add even more confusion to the issue. Mutex conceptually is
designed to be used for MUTual EXclusion of access to a resource (e.g.,
a peace of data). While critical section could be implemented using
mutex, the mutex itself is more general concept. Besides, the rule of
thumb using mutexes is: "protect data, not program code."

My answer to OP's question is: use either lock (mutex) or semaphore.
I'd probably use semaphore as mutexes are usually optimized for the case
when contention probability is low (i.e., they usually shouldn't be locked
for a long time).

--
Sergei.
Jul 18 '05 #4
>>>>> "Sergei" == Sergei Organov <os*@javad.ru > writes:

Sergei> My answer to OP's question is: use either lock (mutex) or
Sergei> semaphore. I'd probably use semaphore as mutexes are
Sergei> usually optimized for the case when contention probability
Sergei> is low (i.e., they usually shouldn't be locked for a long
Sergei> time).

Both Mutexes and Semaphores put the thread to sleep, so I don't think
there will be a big difference.

The OP might also want to check out read/write lock. The first thing
google finds is

http://www.majid.info/mylos/weblog/2004/11/04-1.html

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #5
Ville Vainio <vi***@spammers .com> writes:
>> "Sergei" == Sergei Organov <os*@javad.ru > writes:


Sergei> My answer to OP's question is: use either lock (mutex) or
Sergei> semaphore. I'd probably use semaphore as mutexes are
Sergei> usually optimized for the case when contention probability
Sergei> is low (i.e., they usually shouldn't be locked for a long
Sergei> time).

Both Mutexes and Semaphores put the thread to sleep, so I don't think
there will be a big difference.


Yeah, most probably from this point of view there is no difference
(mutexes could be implemented using busy-waiting, but I don't think it's
the case). However, though I don't think it's a real issue in this
particular case either, mutexes can do fancy things with the thread that
has locked the mutex (mutex owner thread), like raising its priority to
the highest one of the threads waiting for the mutex to prevent so
called priority inversion.

There could be other subtle differences between mutex and semaphore
behavior resulting in different performance of the application. The
application correctness shouldn't be affected though.

--
Sergei.
Jul 18 '05 #6

Pierre Barbier de Reuille <pi************ @cirad.fr> wrote:

Ville Vainio a écrit :
>>>"Bastia n" == Bastian Hammer <we*******@haus tierworld.de> writes:



Bastian> Now I have to make sure, that both threads are
Bastian> synchronal, 1 thread edits something and the other is
Bastian> blocked until the first thread is ready.

Bastian> Isn´t it a good idea to do this with a semaphore?

Semaphore will do, but this is a classical use case for
threading.Lock.

There should be lots of stuff regarding locks (or more googleably,
"mutexes") on the net.


I don't agree. Mutexes (or locks) are best suited for critical sections
(ie. sections that cannot be run by many thread at the same time). The
kind of synchonisation Bastian want is not really semaphore either but
more event. This python "Event" object is described in the section 7.5.5
of the documentation of Python 2.3. There is no example, but I think
Event are quite strait forward : you creates it, then some thread block,
waiting the event to occure while some other thread execute until it set
the event, allowing the blocked thread to go on its own execution :)


You can agree or disagree as much as you want. Fundamentally, they are
all equivalent.

The only thing that makes mutex 'special' is that one can have an
optional 'call this function with this argument when it gets the lock',
but that can be implemented with a standard Lock, Condition, Event,
Semaphore, etc.
- Josiah

Jul 18 '05 #7
Sergei Organov a ecrit :
Pierre Barbier de Reuille <pi************ @cirad.fr> writes:

Ville Vainio a ecrit :
>>>>"Bastia n" == Bastian Hammer <we*******@haus tierworld.de> writes:

Bastian> Now I have to make sure, that both threads are

Bastian> synchronal, 1 thread edits something and the other is
Bastian> blocked until the first thread is ready.
Bastian> Isn't it a good idea to do this with a semaphore?

Semaphore will do, but this is a classical use case for
threading.Lo ck.

There should be lots of stuff regarding locks (or more googleably,
"mutexes") on the net.

I don't agree. Mutexes (or locks) are best suited for critical sections (ie.
sections that cannot be run by many thread at the same time).

Please don't add even more confusion to the issue. Mutex conceptually is
designed to be used for MUTual EXclusion of access to a resource (e.g.,
a peace of data). While critical section could be implemented using
mutex, the mutex itself is more general concept. Besides, the rule of
thumb using mutexes is: "protect data, not program code."

My answer to OP's question is: use either lock (mutex) or semaphore.
I'd probably use semaphore as mutexes are usually optimized for the case
when contention probability is low (i.e., they usually shouldn't be locked
for a long time).


My point is : semaphore is more complex than what he needs. Event are
simpler and just do what he needs : block one thread until another one
finished some jobs and launchs the event (have a look at my example).

Afterward, I agree that the concept of mutex is the most general : you
can implement every other kind of lock using just mutexes.

Pierre
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3901
by: dede | last post by:
Dear community, having written a working example for using Semphores on a windows client, I created a little "server-application" that does the following: A Server continously "listens/tails" a command-file for new commands. If a new commands arrives a split of the workload to threads is under- taken that "control themselves" via Semaphore and are joined finally. It works.
1
2646
by: rushik | last post by:
Hello all, I m facing an interesting problem related to semaphore in php. We are using a huge business application running on LAMP. For database operations we are maintaining centralized DB manager classes in php which perform all the single table related activity. Before inserting new record we are acquiring semaphore on specific key (all the tables are having seprate sem keys), insert the record and release the semaphore.
5
4607
by: marvind | last post by:
I tried using a Semaphore class (have included the full listing reproduced from article Figure 1 at the end of this email) in .NET 1.1. It works fine most of the time, however, I see the following error occassionally: 08/28/2005 17:32:42.82, Verbose, QueryObject.MergeSubQuery, Exception: Too many posts were made to a semaphore in mscorlib. Server stack trace:
5
2523
by: Unni | last post by:
Hello all, I m facing a memory related problem with semaphores. Our business application uses semaphores extensively and the limit imposed by the OS on the number of semaphores that can exist on the system is only 128. This could be increased to a higher value but that would not be a permanant solution to my belief. We are using the sem_get, sem_acquire php functions. After the use we are releasing the semaphore by using sem_release.
2
2146
by: techi_C | last post by:
Hi I'm getting a problem while removing semaphore from system. Before removing semaphore I'm checking the usage count of a smaphore. // checking usage count usage_count = semctl(sem_ptr->semid, 1, GETVAL, NULL); if( usage_count 1 ) // return don't remove semaphore else
1
2272
by: cranfic | last post by:
Please help... To make it simple, I have a simple test C program which calls my semphore library functions only. (It doesn't call any db2 function at all). And the following is the test program: #include "hasem.h" #include <semaphore.h> #include <stdio.h>
0
973
by: sukasa | last post by:
Greetings. After first noticing a malfunction in my application, I ran some tests which have given me the following insights on the code performance: -The " infinite" loop which waits on the semaphore first thing in every iteration, may succeed in going through several iterations. -The number of successful iterations may differ with every execution, as well as with timing differences caused by the different placement of breakpoints. ...
0
2251
by: Samuel R. Neff | last post by:
I'm having trouble creating a Semaphore with read-access rights for everyone. Originally I was trying to use this code: semaphore = new Semaphore(maxLocks, maxLocks, "RwLock#" + name); but when using that code to create a Semaphore instance for an existing system semaphore (i.e., the second time the code gets hit), I get an UnauthorizedAccessException. So I tried specifying that everyone has read rights:
5
2723
by: GHUM | last post by:
hello, in my application I am using hSem = win32event.CreateSemaphore (None, 1, 1,"stringincludinginterfaceandport") rt=win32event.WaitForSingleObject (hSem, 0) if rt != win32event.WAIT_TIMEOUT: really_do_start_my_app() else:
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10039
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6668
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3955
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.