473,666 Members | 2,039 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C or C++ program?

I need some advice regarding a coding requirement that may suggest the
need for an object oriented solution. The code fragments presented
here attempt to solve the problem in C.

The problem:

Data Packets are received from a socket and consist of 3 elements: the
Packet Type, the "Item", and some Data.

The Packet type represents either:

(1) A Task to be performed on the Item using the supplied Data
(2) A Condition that has arisen for the Item
(3) A signal to exit

A Task triggers a function that executes code based on the Packet's
Item and Data. Often the Task will trigger, and must wait for,
additional Packets to satisfy certain Conditions before the Task can
complete. The number of Conditions and the length of time spent
waiting will vary for each Task. In this example, there is a "simple"
Task that waits for one condition and a "complex" Task that waits for
2 conditions at different points of processing. In the actual
implementation, there would be many more Tasks, some with 3 or more
Conditions.

Listing 1 represents what I know will not work but illustrates the
problem. Listing 2 represents the best way I've come up with to handle
this in C.

Is Listing 2 a sound approach?
Is there a better way in C?
Would it be much easier in C++ or another "object oriented" language?

Thanks a million!

-Kerry
----------
Listing 1:
----------

As Packets are received, the appropriate function is called for
processing. During processing, additional Packets are received from
within the functions so that the Task can wait for the appropriate
condition(s) and Data before continuing the Task.

A fundamental problem with this approach is that while a function is
waiting for additional Packets to indicate the desired Condition, a
Packet may arrive for some other Item. Handling the new Packet within
the function seems impossible - what if the desired Condition for the
first Packet arrives during the processing of the second?

I could store incoming Packets that I'm not ready for and process them
after the pending Task has completed but that could lead to
"deadlocks" if the new Packet was meant to supercede the first. At
best, the new Tasks would be unnecessarily delayed since they'd have
to wait for the pending Task's Conditions to be met.

// Define Packet Structure

struct stx
{ int ptype;
int item;
int data;
};

// Define Packet Types

int DoSimpleTask = 0;
int DoComplexTask = 1;
int DoOtherTask = 2;
int ConditionA = 3;
int ConditionB = 4;
int ConditionC = 5;
int DoExit = 6;

struct stx x;

..
..
..
do
{
x = BlockForNextPac ket();

switch (x.ptype)
{
DoSimpleTask: rc = funcDoSimpleTas k(x.item, x.data);
break;

DoComplexTask: rc = funcDoComplexTa sk(x.item, x.data);
break;

DoOtherTask: rc = funcDoOtherTask (x.item, x.data);
break;

DoExit: rc = funcExit();
break;

default: break;
}
}
while (x.ptype != DoExit)
..
..
..

int funcDoSimpleTas k(int i, int d)
{
// Perform Task here

// Wait until Condition A for this item exists
do
{ x = BlockForNextPac ket(); }
while ( (x.item != i) || (x.ptype != ConditionA) )

// Perform post-Task processing here

return 0;
}

int funcDoComplexTa sk(int i, int d)
{
struct stx x;

// Perform 1st part of Task here

// Wait until Condition A for this Item exists
do
{ x = BlockForNextPac ket(); }
while ( (x.item != i) || (x.ptype != ConditionA) )

// Perform 2nd part of Task here

// Wait until Condition B for this Item exists
do
{ x = BlockForNextPac ket(); }
while ( (x.item != i) || (x.ptype != ConditionB) )

// Perform post-Task processing here

return 0;
}

int funcDoOtherTask (int i, int d)
{
// Perform complete Task here and exit immediately

return 0;
}


----------
Listing 2:
----------

All Packets are received within a single loop. Tasks have been broken
up into fragments so that none of them require fetching additional
Packets. Since certain Packets (Condition A for instance) can mean
different things at different times, an array has been added to
maintain the State of incomplete Tasks. While all Tasks are handled
correctly, the overhead needed to maintain State is confusing, even in
this simplistic example.

Although it's not handled here for the sake of brievity, if a new Task
arrives for an Item that is already in a pending State, either the new
or old Task would need to be aborted. Identifying and handling these
situations seems possible since the State arrays are in scope when the
new Task arrives.

..
..
..

int SimpleTaskState[number-of-items];
int ComplexTaskStat e[number-of-items];

do
{
x = BlockForNextPac ket();

switch (x.ptype)
{
DoSimpleTask: { rc = funcDoSimpleTas k(x.item, x.data);
// Update State - waiting for Cond A
SimpleTaskState[x.item] = 1;
break;
}

DoComplexTask: { rc = funcDoComplexTa sk(x.item, x.data);
// Update State - waiting for Cond A
ComplexTaskStat e[x.item] = 1;
break;
}

DoOtherTask: { rc = funcDoOtherTask (x.item, x.data);
break;
}

DoExit: { rc = funcExit();
break;
}

ConditionA: { if ( SimpleTaskState[x.item] == 1 )
{ // Simple Task was waiting for Cond A
// Now finish the Task
rc = funcDoSimplePos t(x.item, x.data);
// Task complete, reset State
SimpleTaskState[x.item] = 0;
}
else if ( ComplexTaskStat e[x.item] == 1 )
{ // Complex Task was waiting for Cond A
// Now do part 2 of Task
rc = funcDoComplexPa rt2(x.item, x.data);
// Part 2 complete, now waiting for Cond B
ComplexTaskStat e[x.item] = 2;
}
else
{ // Condition A is irrelevant right now
}
break;
}

ConditionB: { if ( ComplexTaskStat e[x.item] == 2 )
{ // Complex Task was waiting for Cond B
rc = funcDoComplexPo st(x.item, x.data);
// Task complete, reset state
ComplexTaskStat e[x.item] = 0;
}
else
{ // Condition B is irrelevant right now
}
break;
}

default: break;
}
}
while (x.ptype != DoExit)
..
..
..

int funcDoSimpleTas k(int i, int j)
{
// Perform Task here
return 0;
}

int funcDoSimplePos t(int i, int j)
{
// Perform post-Task processing here
return 0;
}

int funcDoComplexTa sk(int i, int j)
{
// Perform 1st part of Task here
return 0;
}

int funcDoComplexPa rt2(int i, int j)
{
// Perform 2nd part of Task here
return 0;
}

int funcDoComplexPo st(int i, int j)
{
// Perform post-Task processing here
return 0;
}

int funcDoOtherTask (int i, int j)
{
// Perform complete Task here and exit immediately

return 0;
}
Nov 13 '05 #1
3 2159
Below is a sample of data that would be supplied to my program. The
sequence and packet columns are added for clarity - the algorithm as
written doesn't need these values for anything. Since the data has no
effect on the routing of packets, I made them all 0 for the example.
Seq packet ptype item data

1 1 simple 1 0
2 a 1 0

2 3 complex 1 0
4 a 1 0
5 b 1 0

3 6 simple 1 0
7 complex 2 0
8 a 1 0
9 a 2 0
10 b 2 0

4 11 complex 1 0
12 complex 2 0
13 a 2 0
14 a 1 0
15 b 1 0
16 simple 1 0
17 b 2 0
18 a 1 0

5 19 complex 1 0
20 b 1 0
21 a 1 0
22 b 1 0
In the first sequence of Packets, a Simple Task is initiated for Item
1 immediatedly followed by Condition A for Item 1 and the Task
completes.

In the second sequence, a Complex Task is initiated for Item 1
immediately followed by Condition A then Condition B and the Task
completes. When Packet 4 arrives, the State of Item 1 is examined to
determine which routine to call since "Condition A" can mean "complete
simple task" or "proceed with complex task" depending on the State.

In the third sequence, a Simple Task is initiated for Item 1 followed
by a Complex Task initiation for Item 2 before Item 1's Task has
completed. The State of each Item is maintained as "waiting for
condition a". When Packet 8 arrvies, Item 1's Simple Task completes.
Packets 9 and 10 provide the conditions for Item 2's Complex Task to
complete.

In the forth sequence, Item 2's first condition is satisfied before
Item 1's however the next 2 Packets allow Item 1's Task to complete
before Item 2. Before Item 2 receives it's final Condition in Packet
17, Item 1 has a new Task begun in Packet 16.

In the final sequence, Condition B arrives before Condition A. The
Condition is ignored as it's meaningless in the Item's current state.
When it arrives again as the last Packet, the Task completes.
Nov 13 '05 #2
Kerry wrote:
I need some advice regarding a coding requirement that may suggest the
need for an object oriented solution. The code fragments presented
here attempt to solve the problem in C. [snip]

Is Listing 2 a sound approach?
Is there a better way in C?
Would it be much easier in C++ or another "object oriented" language?

Thanks a million!

-Kerry

[snip -- long listings of code]

The term "better" is a vague term.
What is your explanation of "better"?
Do you want your code optimized for speed?
Do you want your code optimized for space?
Do you want code that is more readable?
Is code that can be developed faster with
good quality better?
Does your code work correctly?
Does your code handle all user possiblities
without crashing?
Can portions of your code be reused without
modification?

If the code is for a business, then I suggest you
hold a code review with your peers. If your code
works correctly, then move on to other parts of
the project. Don't optimize working code, unless
absolutely necessary. Most of a program's development
cost is your time. The more time you waste performing
unneeded optimizations, the more the program will
cost and the delivery date will be postponed.

If your programm has duplicate code fragments, but
it works correctly, then you are done. After you are
finished have the time (or can paid for the extra time)
then go ahead and optimize it. Just remember, once a
working program is modified in any manner, it must be
retested all over again, a.k.a. regression testing.

My hobby project has never been released in 20 years
because I keep optimizing, redesigning and starting
over. But then, I am using it as a learning tool.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 13 '05 #3
> The term "better" is a vague term.
What is your explanation of "better"?


Readabilty may best describe what I dislike about my solution. The
1st listing was more readable in that there was a specific routine to
handle each task. One could examine the code for a routine and easily
determine what conditions need to be satisfied (and in what order) for
the task to complete. But it doesn't allow for multiple incomplete
tasks to co-exist, hence listing 2.

I was hoping that someone would see what I'm trying to accomplish and
say "Oh, that's a classic example of (some common scenerio) which is
most often handled with (some known algorithm)". The problem I've
described doesn't seem terribly unique - just unique in MY experience.
Thanks for the advice, Thomas.

-Kerry
Nov 13 '05 #4

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

Similar topics

2
14159
by: Mike | last post by:
I am sure that I am making a simple boneheaded mistake and I would appreciate your help in spotting in. I have just installed apache_2.0.53-win32-x86-no_ssl.exe php-5.0.3-Win32.zip Smarty-2.6.7.tar.gz on a system running WindowsXP SP2. Apache and PHP tested out fine. After adding Smarty, I ran the following http://localhost/testphp.php
22
3593
by: edgrsprj | last post by:
PROPOSED EARTHQUAKE FORECASTING COMPUTER PROGRAM DEVELOPMENT EFFORT Posted July 11, 2005 My main earthquake forecasting Web page is: http://www.freewebz.com/eq-forecasting/Data.html Newsgroup Readers: If you circulate copies of this report to groups of computer programmers at different universities etc. around the world then they might find the subject matter to be interesting.
0
6117
by: Tom Lee | last post by:
Hi, I'm new to .NET 2003 compiler. When I tried to compile my program using DEBUG mode, I got the following errors in the C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7 \include\xdebug file as folows. I need help to resolve them ASAP: cl /c /nologo /MDd /W3 /Od /GR /GM /Zi /GX /D "_DEBUG" /D " WIN32" /D "_W INDOWS" /D "_WINDLL" /D "_AFXDLL" /D "_MBCS" /D "_USRDLL" /
11
2598
by: christopher diggins | last post by:
I am wondering if any can point me to any open-source library with program objects for C++ like there is in Java? I would like to be able to write things like MyProgram1 >> MyProgram2 >> Fork(MyProgram3, SomeFile); If not would this be something of interest to others? Thanks in advance,
1
3261
by: Eric Whittaker | last post by:
hi all, im trying to write my first c++ program. a success, but i can't get the window to stay open after user enters input. it just automatically closes. right now the end of my program looks like this: return 0; }
9
4526
by: Hemal | last post by:
Hi All, I need to know the memory required by a c program. Is there any tool/utility which can give me the memory usage in terms of DATA segment, TEXT segment, BSS segment etc. I am working on linux platform and my target is ARM processor. But i guess it should not matter. Actually i need to know both RAM & ROM usage.
7
13263
by: ibtc209 | last post by:
I just started programming in C, and I need some help with this problem. Your program will read the information about one MiniPoker hand, namely the rank and suit of the hand’s first card, and the rank and suit of its second card. Note that the two cards in a hand may be entered in any order; it’s not necessarily the case that the highest card will appear first, for example. Your program will then determine whether the hand is valid, and...
2
19338
Banfa
by: Banfa | last post by:
Posted by Banfa The previous tutorial discussed what programming is, what we are trying to achieve, the answer being a list of instructions constituting a valid program. Now we will discuss how we set about doing that. Every program starts with a specification, this may be a several hundred page document from your latest client or one small paragraph from your professor and pretty much anything in-between. The specification is very...
0
13327
amitpatel66
by: amitpatel66 | last post by:
There is always a requirement that in Oracle Applications, the Concurrent Program need to be execute programatically based on certain conditions/validations: Concurrent programs can be executed programatically either from UNIX or Oracle PLSQL. In this Section, I will be explaining about calling a Concurrent program from UNIX using the CONCSUB Command. Pre-requisite: 1. Concurrent Program should be registered in oracle Applications...
0
8448
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
8356
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
8871
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...
1
8552
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
7387
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
4198
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
2773
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
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1776
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.