473,616 Members | 2,973 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Atomic operations and Thread safe code

consider this code :

int i; //gobal var

Thread1:
i=some value;

Thread2:
if (i==2) dosomething();
else dosomethingelse ();

I want to write it to be thread safe without using synchronization
objects.

my questions are:

1) is an assignment operation of an int atomic in c/c++?
if so will thaat code work?

volatile int i;

int getI()
{ return i;//assignment is atomic so assignment to return
value will be atomic also
}

void setI(int somevalue)
{
i=somevalue;//assignment atomic
}

Thread1:
setI(somevalue) ;

Thread2:
if (getI()==2) dosomething();
else dosomethingelse ();
2) what operations in c are atomic?
are mailslots pipes etc operations atomic/threadsafe ?
thanks.

Katy.

Mar 25 '06 #1
6 6243
bl************@ hotmail.com wrote:
consider this code :

int i; //gobal var

Thread1:
i=some value;

Thread2:
if (i==2) dosomething();
else dosomethingelse ();

I want to write it to be thread safe without using synchronization
objects.

my questions are:

1) is an assignment operation of an int atomic in c/c++?
if so will thaat code work?
No and no.
volatile int i;

int getI()
{ return i;//assignment is atomic so assignment to return
value will be atomic also
}

void setI(int somevalue)
{
i=somevalue;//assignment atomic
}

Thread1:
setI(somevalue) ;

Thread2:
if (getI()==2) dosomething();
else dosomethingelse ();
2) what operations in c are atomic?
are mailslots pipes etc operations atomic/threadsafe ?


Modifications of objects of type sig_atomic_t (C99) are atomic in C. As
for C++ ask in a C++ newgroup.

However simply using atomic objects doesn't garuntee synchronisation
and threads as well as thread safe code are outside the scope of
standard C. Generally, you'll have to use external libraries like
pthreads or make use of specific API functions of your underlying
operating system.

For further questions on this topic please try to confine your postings
to more relavent groups like comp.programmin g.threads etc.

Mar 25 '06 #2
bl************@ hotmail.com schrieb:
consider this code :

int i; //gobal var

Thread1:
i=some value;

Thread2:
if (i==2) dosomething();
else dosomethingelse ();

I want to write it to be thread safe without using synchronization
objects.

my questions are:

1) is an assignment operation of an int atomic in c/c++?
if so will thaat code work?


I can't speak for C++, but probably the situation is similar;
ask in comp.lang.c++ to be sure.
In standard C, there are no threads; the C99 standard speaks
only of atomic operations with respect to contraction of
floating expressions.
Ask in a newsgroup for your operating system for the respective
brand of threads etc.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Mar 25 '06 #3
Michael Mair wrote:
.... snip ...
the C99 standard speaks only of atomic operations with
respect to contraction of floating expressions.


I may have misunderstood, but what about operations on objects of type
<i>sig_atomic_t </i>?

Mar 25 '06 #4
In article <11************ *********@z34g2 000cwc.googlegr oups.com>,
santosh <sa*********@gm ail.com> wrote:
Modification s of objects of type sig_atomic_t (C99) are atomic in C.


I do not have my C89 standard handy at the moment. My recollection
is that in C89, the atomicity promises on sig_atomic_t only
hold in signal handlers and only for volatile sig_atomic_t.
The types of operations that are atomic
are restricted, but I do not recall the details at the moment.

The OP wanted to use atomic operations without using a synchronization
object. In C89, the minimum is to use a signal handler -- but if one
is using multiple threads then [generally speaking] one might be using
multiple processes, so it is possible that there are multiple signal
handlers active at any one time, so signal handlers should not be
considered to be a stand-in for thread synchronization .

In short, to do anything -useful- with sig_atomic_t requires relying
on implementation-specific extensions... and if you have those then
you should probably use a implementation-specific synchronization
primitive rather than risking very subtle race conditions that you
did not happen to think of.
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
Mar 25 '06 #5
santosh schrieb:
Michael Mair wrote:
... snip ...
the C99 standard speaks only of atomic operations with
respect to contraction of floating expressions.


I may have misunderstood, but what about operations on objects of type
<i>sig_atomic_t </i>?


Hmmm, good point. In principle, you have an integer type that
is an atomic entity w.r.t. _access_, even if you have interrupts.
The only kind of operations that do not have undefined behaviour
is assignment of a value to an object of type volatile sig_atomic_t.
This is effectively useless for meaningful portable programs --
as is the whole standard conforming part of C signal handling.

I consider <signal.h> as a suggestion how signal handling should be
done so that porting does not become too hard.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Mar 25 '06 #6
In article <e0**********@c anopus.cc.umani toba.ca>,
Walter Roberson <ro******@ibd.n rc-cnrc.gc.ca> wrote:
The OP wanted to use atomic operations without using a synchronization
object. In C89, the minimum is to use a signal handler -- but if one
is using multiple threads then [generally speaking] one might be using
multiple processes, so it is possible that there are multiple signal
handlers active at any one time, so signal handlers should not be
considered to be a stand-in for thread synchronization .


Sorry, that should have read "multiple processors", not "multiple
processes". Some threading libraries can only have one of the threads
executing at any one instant, but other threading libraries can
distribute to multiple processors, with all the race conditions that
that implies.
Hmmm, I remember a second ago that the last time around we had
the atomicity debate, someone posted a reference to a software-only
synchronization method. It wasn't clear to me from the papers
whether that applied on multiple processors.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Mar 26 '06 #7

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

Similar topics

5
5271
by: Paul Moore | last post by:
I can't find anything which spells this out in the manuals. I guess that, at some level, the answer is "a single bytecode operation", but I'm not sure that explains it for me. This thought was triggered by a comment on the Python Cookbook site, which basically said that it was OK to do tss = {} ... id = thread.get_ident() tss = {}
8
3571
by: Glenn Kasten | last post by:
I am wondering which operations in Python are guaranteed to be atomic in the presence of multi-threading. In particular, are assignment and reading of a dictionary entry atomic? For example, initially: dictionary = {} dictionary = old_value Then thread 1 does: v = dictionary And thread 2 does:
42
3337
by: Shayan | last post by:
Is there a boolean flag that can be set atomically without needing to wrap it in a mutex? This flag will be checked constantly by multiple threads so I don't really want to deal with the overhead of mutexes or semaphores. Thanks. Shayan
28
7370
by: robert | last post by:
In very rare cases a program crashes (hard to reproduce) : * several threads work on an object tree with dict's etc. in it. Items are added, deleted, iteration over .keys() ... ). The threads are "good" in such terms, that this core data structure is changed only by atomic operations, so that the data structure is always consistent regarding the application. Only the change-operations on the dicts and lists itself seem to cause problems...
0
388
by: blackstreetcat | last post by:
consider this code : int i; //gobal var Thread1: i=some value; Thread2: if (i==2) dosomething(); else dosomethingelse();
3
2238
by: Ole Nielsby | last post by:
I need to implement reference counting in a class hierarch, in a thread safe manner. (The classes are umanaged but I might want to compile them with the /clr option.) Some of the objects - atoms - are registered in a global hash table - let's call it an atom table. When an atom refernce count reaches zero, the atom is removed from the table. The catch is, after an atom has been counted down, another thread might find it in the atom...
9
15051
by: Dave Stallard | last post by:
Pardon if this is the wrong newsgroup for this question, and/or if this question is naive. I have a multi-threaded Windows application in which certain variables/object fields are shared: one thread may write the variable, and the other thread read it. The variables in question may have int or int* types. Question: Is it safe to do this? Or is it possible a read that happens at the same time as a write may retrieve a scrambled value,...
11
2062
by: japhy | last post by:
Is there a way to read a line (a series of characters ending in a newline) from a file (either by descriptor or stream) atomically, without buffering additional contents of the file?
11
6325
by: Jon Harrop | last post by:
Can read locks on a data structure be removed safely when updates are limited to replacing a reference? In other words, is setting a reference an atomic operation? I have been assuming that all writes of <=1 word of data are atomic. Is this actually documented anywhere? -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com/products/?u
0
8203
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8146
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
8592
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
8297
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
8449
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
7121
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
6097
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
4063
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...
0
1445
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.