473,806 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threads: not locking read-only objects

Is it safe to not put a lock on an object if it will always
be read-only in other threads and will only ever be written to
in just one and always the same one thread?
Jul 18 '05 #1
3 1552
On Sat, 7 Aug 2004, Jon Perez wrote:
Is it safe to not put a lock on an object if it will always
be read-only in other threads and will only ever be written to
in just one and always the same one thread?


Only if the writes are guaranteed to be atomic: if the object is ever
temporarily left in an inconsistent state by the writer (due to a thread
switch), the readers will read inconsistent data. If you are sure this
can't happen, then yes, doing so is safe.

Jul 18 '05 #2
Hmmm... here's what's going on. I have a dictionary of
logged in users called 'whoison' that's updated in the main
thread (and only in the main thread) with a:

whoison['username']="timeoflogi n" # to add someone new

and

del whoison['username'] # to remove someone who's logged out
Do the above count as atomic?
The worker threads do the following read-only operation:

for x in whoison:
print x,whoison[x]

Looking at the read-only code though I just realized
something.... if a dictionary entry in 'whoison' is deleted
by the main thread while the 'for x in whoison' is executing
then what would happen?

Looks like I'm going to need a lock after all even for the
read-only operations...?

Christopher T King wrote:
On Sat, 7 Aug 2004, Jon Perez wrote:

Is it safe to not put a lock on an object if it will always
be read-only in other threads and will only ever be written to
in just one and always the same one thread?

Only if the writes are guaranteed to be atomic: if the object is ever
temporarily left in an inconsistent state by the writer (due to a thread
switch), the readers will read inconsistent data. If you are sure this
can't happen, then yes, doing so is safe.

Jul 18 '05 #3
Am Samstag, 7. August 2004 04:58 schrieb Jon Perez:
whoison['username']="timeoflogi n" # to add someone new

del whoison['username'] # to remove someone who's logged out

Do the above count as atomic?
Yup, both of them are atomic. But: If you use different dictionary keys than
strings, you're in for a little surprise, as __hash__ing an object can cause
Python to be called, which might be suspended by a thread switch.

The dictionary object will still be in perfect order (it'll never be in an
inconsistent state), but the key reference won't be in the dictionary yet.
for x in whoison:
print x,whoison[x]

Looking at the read-only code though I just realized
something.... if a dictionary entry in 'whoison' is deleted
by the main thread while the 'for x in whoison' is executing
then what would happen?


Now, this is something different. You can easily try what happens by doing the
following:

whoison = {"heiko":"at home","heiko2": "at work"}
for x in whoison:
print x, whoison[x]
del whoison[x]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
RuntimeError: dictionary changed size during iteration

That's the same exception you'll get when another thread changes the python
dict while you're iterating over it.

What you might do:

# The following makes a static copy of the keys of the dictionary.
for x in whoison.keys():
try:
val = whoison[x]
except KeyError:
continue
print x, val

Or just acquire a thread lock before processing the dictionary, which might
actually be the easiest solution. ;)

Heiko.
Jul 18 '05 #4

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

Similar topics

29
3239
by: Jeffrey Maitland | last post by:
Hello all, I am in the process of writing a multithreading program and what I was wondering is a sleep command in an executing function will affect the threads below it? Here is a basic example of what I mean. def main(): temp_var = True while temp_var == True: if
6
2229
by: Evan David Light | last post by:
After agonizing over this problem for a few days, I've decided to seek help. No, not the variety that involes a jacket that zips up the back but this august body of intrepid individuals. I've discovered the following: - My compile line should resemble: CC -D_PTHREADS -D_POSIX_C_SOURCE=199506L -LANG:std -n32 -mips3 -c <src> -o <obj> - My link line should resemble: CC -LANG:std -n32 -mips3 <objs> -o <executable> -lpthread
9
1884
by: David Poundall | last post by:
I have a thread class and I want to be able to track its usage within an application. FYI the class launches aplications in their own thread when the 'launch' method is called. That works OK However I want to take things a bit further and my thinking was that I could use a class parameter to do a count but I am having no luck I am afraid.
1
1690
by: Tim Smith | last post by:
Hi, I am so far familiar with the C# lock keyword, which I understand prevents any other thread from entering the portion of code which is locked, assuming you are locking the same object instance. I have a cache of data which initially I locked when I write to it, and I locked the same object for any reading. But this will soon become a performance issue, as many threads need to
13
2523
by: orekin | last post by:
Hi There I have been programming C# for a couple of months and am trying to master Threading. I understand that ThreadPool uses background threads (see code example in MSDN page titled 'ThreadPool Class ') .... however I would like to ensure that all my ThreadPool threads have completed before I exit my Main function.
8
2003
by: raghu | last post by:
Hello Everyone I am working on C platform for a project in that project I need to maintain 'n' number of states where n is a dynamic value simultaneously. But I should not use any kind of threads since number of threads allowed, in the project, already reached and I can't predict how many threads to be maintained in this case. Can you please pull me out of this problem. Thanks in adv
41
2125
by: Carl J. Van Arsdall | last post by:
Hey everyone, I have a question about python threads. Before anyone goes further, this is not a debate about threads vs. processes, just a question. With that, are python threads reliable? Or rather, are they safe? I've had some strange errors in the past, I use threading.lock for my critical sections, but I wonder if that is really good enough. Does anyone have any conclusive evidence that python threads/locks are safe or unsafe?
5
2615
by: Benjamin | last post by:
I'm writing a search engine in Python with wxPython as the GUI. I have the actual searching preformed on a different thread from Gui thread. It sends it's results through a Queue to the results ListCtrl which adds a new item. This works fine or small searches, but when the results number in the hundreds, the GUI is frozen for the duration of the search. I suspect that so many search results are coming in that the GUI thread is too busy...
3
1599
by: Lilith | last post by:
Maybe I'm making some assumptions about how threads work. I have a form that, on the press of a button, starts monitoring some SMTP connections. On occasions I make changes while the thread is running in the background. To reload the changed options I have to exit the function the thread is running and restart it. I have an indicator that tells me the function is exiting. But on restart I get an exception that, to the best of my...
0
1839
by: moltendorf | last post by:
I've been trying to find a suitable method for preventing race conditions in my own code. Currently I'm using a file and the flock function to prevent code in other threads from executing at the same time. For example: <?php $pointer = fopen ('./thread.lock', 'a+'); flock ($pointer, LOCK_EX);
0
9598
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
10623
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
10371
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...
0
10111
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9192
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...
0
6877
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();...
0
5546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4330
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
3
3010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.