473,808 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread variable question

I am new to threading and trying to figure some things out. Are all
variables in a thread set to only that thread? Meaning if I create 2
instances of a class and then put each one in a different thread and
run them will the local variables in functions be shared or will they
be thread safe?

Sep 1 '06 #1
6 5817
Each thread will have it's own stack and set of registers. The other
components are down to how you write your code. A penalty occurs when a
thread context switches but that is a different story.

If you create two threads with instances of class X then they each will own
totally separate instances of X. All calls will operate as in a single
threaded application provided that they are not sharing resources! The code
of X may be shared but the data will be totally separate.

If X has a constructor that takes an object Y and for each of the classes
above you provide the same Y object then this becomes a shared resource
(shared resources can be databases, files, handles, registry anything where
a potential collision could occur (i.e. two threads trying to write to the
same stream isn't a good idea)).

Say that Y is a counter for the number of times something happens (an
instance of where you would want a single instance shared). In this scenario
Y is a shared object and just doing count++ is a property or method is not
going to cut it.

You get nasty things like race conditions where both threads try and update
the count at exactly the same time. It may not happen very often but you can
lose data, get random crashes and unpredictable behaviour.

What we need to do is either make Y thread safe or serialise access to the
shared components.

In our example in class Y with the counter property we can either:

1. lock the object. This is a Monitor or Critical section and will prevent
any other threads in whilst a thread owns it. If another thread comes along
while a thread is owning the lock then it will block (wait until it becomes
free) otherwise it will claim the lock and execute the code (hence only one
thread can be executing the code within the lock statement).

public void IncrementCounte r()
{
lock(y) { this.counter++; }
}

2. The Interlocked class provides some atomic functions for manipulating
simple scalar types (Int32, Int64) etc. The operations take exactly one
clock tick so there is no chance of two threads getting part way through an
operation (i.e. as in load value, increment, store value; it's just
increment value).

public void IncrementCounte r()
{
Interlocked.Inc rement(this.cou nter);
}

There are also lots of classes to control synchronisation (Monitor, Events,
Semaphore, Mutexes) but hopefully the above will get you started.

With different shared resources you get different problems. In memory
objects are fairly easy to serialise but SQL database access need careful
consideration as the database is also obviously multi-user so you shouldn't
need to serialise your code to access it, but depending on what calls you
make you can get into deadlock situations where two threads (or even
different processes on different computers) are going after the same locks
on a shared resource (being a SQL database table).

HTH

- Andy

"Extremest" <dn**********@c harter.netwrote in message
news:11******** **************@ i3g2000cwc.goog legroups.com...
>I am new to threading and trying to figure some things out. Are all
variables in a thread set to only that thread? Meaning if I create 2
instances of a class and then put each one in a different thread and
run them will the local variables in functions be shared or will they
be thread safe?

Sep 1 '06 #2
ok this is my main. What do I have wrong with it?

class Program
{
static string[] categories = { "emulation" , "audio" ,
"console" , "anime" , "xxx" , "tv" , "pictures" , "video" };
static void Main(string[] args)
{
string proc = Process.GetCurr entProcess().Pr ocessName;
// get the list of all processes by that name
Process[] processes = Process.GetProc essesByName(pro c);
// if there is more than one process...
if (processes.Leng th 1)
{
//MessageBox.Show ("Applicatio n is already running");
return;
}
else
{
for (int x = 0; x < categories.Leng th; x++)
{
MasterList master = new MasterList();
Groups groups = new Groups(categori es[x]);
WorkerClass WC1 = new WorkerClass(mas ter, groups);
WorkerClass WC2 = new WorkerClass(mas ter, groups);
WorkerClass WC3 = new WorkerClass(mas ter, groups);
WorkerClass WC4 = new WorkerClass(mas ter, groups);
Thread Worker1 = new Thread(new
ThreadStart(WC1 .Start));
Thread Worker2 = new Thread(new
ThreadStart(WC2 .Start));
Thread Worker3 = new Thread(new
ThreadStart(WC3 .Start));
Thread Worker4 = new Thread(new
ThreadStart(WC4 .Start));
Worker1.Name = "Worker1";
Worker2.Name = "Worker2";
Worker3.Name = "Worker3";
Worker4.Name = "Worker4";
Worker1.Start() ;
Worker2.Start() ;
Worker3.Start() ;
Worker4.Start() ;
Worker4.Join();
Worker3.Join();
Worker2.Join();
Worker1.Join();
Console.WriteLi ne(master.size( ));
master.SetEnume rator();
Updater U1 = new Updater(master, categories[x]);
Updater U2 = new Updater(master, categories[x]);
Updater U3 = new Updater(master, categories[x]);
Thread Updater1 = new Thread(new
ThreadStart(U1. insert));
Thread Updater2 = new Thread(new
ThreadStart(U2. insert));
Thread Updater3 = new Thread(new
ThreadStart(U3. insert));
Updater1.Start( );
Updater2.Start( );
Updater3.Start( );
Updater1.Join() ;
Updater2.Join() ;
Updater3.Join() ;
}
}
}
}

Sep 27 '06 #3
<ad***@binindex .netwrote in message
news:11******** **************@ d34g2000cwd.goo glegroups.com.. .
ok this is my main. What do I have wrong with it?
Why do you think there's something wrong with it?

A suggestion: if you are specific with your question, you are much more
likely to get help. Posting some random chunk of code and asking "what's
wrong with it" is way too vague to be worth the time for anyone to bother
with.
Sep 27 '06 #4
ok to be more clear the threads don't die is what I guess I want to
say. The connections are all still open till the program stops
running. I figured since the threadstate is stopped that it would then
cleanup the thread, but I guess I am wrong about that.

Sep 27 '06 #5

ad***@binindex. net wrote:
ok to be more clear the threads don't die is what I guess I want to
say. The connections are all still open till the program stops
running. I figured since the threadstate is stopped that it would then
cleanup the thread, but I guess I am wrong about that.
What connections? Can you post the code for your Start and insert
methods?

Brian

Sep 28 '06 #6
ok Sorry I figured it out. Forgot to actually close the connections
that were staying open. Have that all fixed now.

Sep 28 '06 #7

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

Similar topics

3
2262
by: R. Rajesh Jeba Anbiah | last post by:
----------------------------------------------------------------- This is the FAQ thread where the FAQ compilation project goes. * If you wish to improve the contents, please copy the whole content, fix it and then post it. When posting, please change the revision number (increase by 1) in the subject line. * If you want to comment, do it without changing the subject line. * Do NOT add new question and answers here. Add here only after...
0
1326
by: fowlertrainer | last post by:
Hello ! I have been created a Zope (Python) Product. But it is must store inner global definitions (some conversion parameters), what I need to change in only one thread, or only once. See below. So: because the Zope is threaded application, the threads are use this product. Possible in same time.
5
1351
by: sathya_me | last post by:
friends, As I was going through a set of past thread I have some doubts in that. The link to the thread is: http://groups.google.co.in/groups?hl=en&lr=&ie=UTF-8&safe=off&th=e0ab565b941afc61&rnum=1 I considered the void pointer is the correct way to use generic type in C programming(correct me if I am wrong.) In the above thread is not it possible to create a
4
6368
by: Marc Missire | last post by:
Hi, I have an issue below I'd love help with, involving a static variable, Application_Start, and a background thread. In global.asax.cs I have a static variable (outside any method) with a default value, such as: private static string serverName = string.Empty;
7
2699
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
7
1737
by: MariusI | last post by:
Are objects implicitly stored in the TLS of the currently running thread? When creating multithreaded applications i get errors when accessing data from a different thread than the thread used to create the objects (which is easely fixed by calling Invoke()). Also, is there a way to acces the thread which created the thread, or in other words: is there a parent/child relationship between threads?
22
4103
by: Morpheus | last post by:
Hi, I have been coding in Windows for many years so have a mindset to it, so forgive any stupid questions. Is it possible to create a multithread application in C++ that is portable (OS/compiler)? In my Windows applications, I use synchronization objects like, mutex, semaphores etc. Is there anything similar in the Standard ANSI C++ or would I be best off doing this myself, possibly creating a new class to handle any critical...
4
1422
by: fniles | last post by:
I create a thread where I pass thru a message. When I click very fast many times (like 50 times) to create 50 threads, the message did not get pass thru ProcessMessage. For example: strBuffer = "#TRADE, D1410-123456, BUY, 1, ESM7, DAY, LIMIT, 1490.00, , , 0, 0, 0, 0, 0, links |52994/25/2007 10:47:17 AM !A", when I trigger to create many threads (like 50), this message did not get to sub ProcessMessage in clsEachMessage. I have added...
19
2327
by: Hapa | last post by:
Does only reading (never writing) of a variable need thread synchronisation? Thanks for help? PS. Anybody knows a Visual C++ news group?
13
11483
by: Henri.Chinasque | last post by:
Hi all, I am wondering about thread safety and member variables. If I have such a class: class foo { private float m_floater = 0.0; public void bar(){ m_floater = true; }
0
9721
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
10631
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
10374
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
10374
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
10114
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
9196
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
5548
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
4331
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
3859
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.