473,695 Members | 1,860 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threads question


assuming code:

int i=0;//global variable

//process 1 //process 2
int num=0; int num=0;
while(i<5){ while(i<5){
num=num+1; num=num+1;
i=i+1; i=i+1;
} }

what is the range of values for num?
it is supposed to be from 0-15, but i dont know why- any thoughts?

Jul 23 '05 #1
3 1357
<ja************ @gmail.com> wrote...
[...]


Threads are off-topic here since C++ does not define anything thread-
related in its Standard. Try comp.programmin g.threads.
Jul 23 '05 #2
ja************@ gmail.com wrote:
assuming code:

int i=0;//global variable

//process 1 //process 2
int num=0; int num=0;
while(i<5){ while(i<5){
num=num+1; num=num+1;
i=i+1; i=i+1;
} }

what is the range of values for num?
it is supposed to be from 0-15, but i dont know why- any thoughts?


Mr. Bazarov is correct as usual, threads are not part of C++ and are
therefore off-topic in a strict sense. However, I'll answer just to
illustrate why threads are tricky in C++ (heck, any language) because
there are no threading primitives...

First, the easy case, suppose process 1 runs to completion (exits the
loop) before process 2 ever gets started. When process 2 finally
starts, i is already equal to 5 so the while loop never executes and num
remains 0.

Now, how do we get a num equal to 15?

Suppose process 1 runs first and gets to the point mid way through
executing the i = i+1 statement. It has read the value (0) of i in to a
register and is about to add 1 to it when its time slice is up and it is
interrupted.

Now process 2 runs for a while, and lets say it loops 5 times, with i
having values:

0, 1, 2, 3, 4

Then just before it can execute the i = i+1 statement, or even after it,
but before it can perform the relational test in the while loop... Its
time slice is up and process 1 runs again.

Process 1 still has the value 0 in the register, its context is
restored, and it resets i to 1 now (not 4 or 5 as process 2 had left it).

Now, in an evenly scheduled round-robin (for same priority levels)
system you'd assume that process 1 would now run to completion. But
lets assume a really pathalogical case. Maybe process 1 gets a tiny
time slice before being interrupted by a higher priority process/thread,
just enough to loop exactly once back to where it was, then the round
robin scheduler moves back to process 2 since 1 had at least some time...

Now process 2 gets to run again. It loops with i values:

1, 2, 3, 4

Before once again giving up to process 1. Now process 1 runs again,
with 1 held in the register... It has the ill fortune to loop exactly
once more... Then process 2 runs again...

2, 3, 4

Then 1, and 2...

3, 4

Then finally 1 and 2 once more...

4

So, how many iterations has process 2 actually made through its loop? 15...

Admittedly, this is an extremely pathalogical case - one that you would
probably never be able to induce during testing, but which would almost
certainly occur in the first week of client/customer use. ;-)

It also illustrates just the tip of the iceberg when it comes to the
difficulties and pitfalls associated with multithreaded programming (or
multiprocess programming with shared memory or other resources). And as
Mr. Bazarov points out, C++ has no help for you. Even programming
languages such as Java with built in threading and synchronization
primitives won't think/design for you.
Jul 23 '05 #3
Phil Staite wrote:
Mr. Bazarov is correct as usual, threads are not part of C++ and are
therefore off-topic in a strict sense. However, I'll answer just to
illustrate why threads are tricky in C++ (heck, any language) because
there are no threading primitives...


Just a touch of theory: Threads are tricky in any language - even those that
claim to support them robustly - when they violate encapsulation. One thread
would prefer to ignore and be ignored by other threads. Instead, a thread
must often use semaphores that couple its private control flow details to
other threads' details.

(BTW - question for Phil: Did you submit a Bug++ of the Month last
millenium? I thought you did, but it's Google-proof.)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 23 '05 #4

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

Similar topics

5
30666
by: Tzach | last post by:
I'm developing a simple Java client that runs over a CORBA server. The main client thread is waiting for notification from this server. On each notification, The client creates a new thread executing some logic with the server and close. Each session spend most of the time waiting for the server. At most there can be ~1000 open session. My questions are: 1. How many threads can be open at the same time (with response time of up to ~1...
2
1461
by: grahamo | last post by:
Hi, I realise that c++ knows nothing about threads however my question is related to an (excellent) article I was reading about threads and C++. For all intents and purposes we can forget the sample at hand is concerned about threads, it could be related to widgets for the purpose of this question (that's so I don't get flamed and told to go to comp.programming.threads :)
10
1676
by: [Yosi] | last post by:
I would like to know how threads behavior in .NET . When an application create 4 threads for example start all of them, the OS task manager will execute all 4 thread in deterministic order manes, OS execute (All have same priority) Thread#1 may be other threads, Thread#2 may be other threads, Thread#3 may be other threads,
1
1718
by: Raoul Minder | last post by:
Hi all I am new to threading! I am developping a newsletter tool including a dispatch manager that should schedule sendings. The Web layer kicks a remote object hosted by a windows service and should 'add' a schedule (time to send, id and so on). The result should be that I have multiple threads waiting for the send time (with thread.sleep). Now the question: How can I abort or change the 'time to send' if the web administrator...
14
3253
by: Lior Amar | last post by:
Quick question about threads and delegates. I have the following scenario Thread A (CLASSA) spawns Thread B (CLASSB) and passes it a DelegateA to a callback Thread B Invokes a DelegateB asynchronously (could be a timer but then we get Thread C) Upon completion of DelegateB, Thread B would like to callback ThreadA using DelegateA but as we all know the call to DelegateA is running in ThreadB. Is
10
1512
by: cj | last post by:
I'm writing a TCP/IP server app that will have many simultaneous connections. The main thread listens for new connections and starts a thread to handle each requested connection. These are short lived threads that get a request and return a reply and end. Can the main thread tell me how many connection threads are currently running at any given time? I'd like to have a label on the main form to show how many connections the server is...
7
3100
by: Michael | last post by:
I'm writing an application that decodes a file containing binary records. Each record is a particular event type. Each record is translated into ASCII and then written to a file. Each file contains the same events. At the moment each record is processed one after the other. It taks about 1m40s to process a large file containing 70,000 records. Would my application benifit from multiple threads and mmap? If so what is the best way to...
1
1398
by: | last post by:
I'm trying to think something through and am wondering if may have some suggestions. I am building a Windows service (VStudio 2005, C#) that uses a COM component to answer a telephone call(s). The aqpplication uses 6 trunk channels for the lines. What I need to do is initialize all 6 lines and set the event handler to witfor/answer the call. I have to pass the trun kchannel to this thread as a parameter. Then, when the phone rings on...
4
4011
by: gsimmons | last post by:
I've been researching multi-threaded WinForms apps and thread synchronization stuff for a couple days since I'm working on refactoring a multi-threaded GUI app at work and want to be sure it's rock solid/thread-safe. I've seen all the posts about using BeginInvoke to have worker threads interact with the UI. My question is this: I created a plain old Windows Form application (VS.NET 2005) with a blank form, built it (release build), ran...
1
4134
by: chunghorng_lung | last post by:
Hi All, I have a question on the scope of variables for threads. The program has a main thread which creates a few worker threads. The main thread can access another class stored in another file, however, the worker threads can't. I got link errors for the code inside of the worker threads. The following contains code segments. Multi_Queue is a class and getXXX() is a public member function inside of Multi_Queue which is in...
0
8590
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
9140
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
9005
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
8845
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
7693
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
5848
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
4603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3025
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
2304
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.