473,396 Members | 1,780 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 5801
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 IncrementCounter()
{
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 IncrementCounter()
{
Interlocked.Increment(this.counter);
}

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**********@charter.netwrote in message
news:11**********************@i3g2000cwc.googlegro ups.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.GetCurrentProcess().ProcessName;
// get the list of all processes by that name
Process[] processes = Process.GetProcessesByName(proc);
// if there is more than one process...
if (processes.Length 1)
{
//MessageBox.Show("Application is already running");
return;
}
else
{
for (int x = 0; x < categories.Length; x++)
{
MasterList master = new MasterList();
Groups groups = new Groups(categories[x]);
WorkerClass WC1 = new WorkerClass(master, groups);
WorkerClass WC2 = new WorkerClass(master, groups);
WorkerClass WC3 = new WorkerClass(master, groups);
WorkerClass WC4 = new WorkerClass(master, 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.WriteLine(master.size());
master.SetEnumerator();
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.googlegr oups.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
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...
0
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...
5
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: ...
4
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...
7
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...
7
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...
22
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...
4
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 =...
19
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
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...

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.