473,721 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Critical Sections & Threading

Hi I am looking for some help
on Threading and Critical Sections

I have a main thread that controls an event

the event handler creates a new thread for carrying out the work

because the work may not be completed before the event is triggered again

I am trying to add critical sections round the producer & consumer parts of
the work

What I am actually looking for is the VC++ syntax for creating the thread &
critical sections

It keeps asking for a second parameter for the theadstart, which is not
needed in C#

and finally the critical section return with not a class or namespace

if anybody can help I would be really grateful

cheers

Michael
Nov 17 '05 #1
6 3261
MPH Computers wrote:
Hi I am looking for some help
on Threading and Critical Sections

I have a main thread that controls an event

the event handler creates a new thread for carrying out the work

because the work may not be completed before the event is triggered again

I am trying to add critical sections round the producer & consumer parts of
the work

What I am actually looking for is the VC++ syntax for creating the thread &
critical sections

It keeps asking for a second parameter for the theadstart, which is not
needed in C#

and finally the critical section return with not a class or namespace

if anybody can help I would be really grateful


Here is a VC++ 2003 example of a multithreading application:
__gc class SomeClass
{
int index;

//...

public:

// ...
void DoSomething()
{
Monitor::Enter( this);

// Modify index

Monitor::Exit() ;
}

void DoSomethingElse ()
{
Monitor::Enter( this);

// Modify index

Monitor::Exit() ;
}

// ...
};
SomeClass *ps= __gc new SomeClass;

// ...

Thread *pthread1= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omething) );

Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omethingElse) );
//Start execution of ps->DoSomething( )
pthread1->Start();

//Start execution of ps->DoSomethingEls e()
pthread2->Start();

// ...
Nov 17 '05 #2
Ioannis Vranos wrote:
Here is a VC++ 2003 example of a multithreading application:


Just to clarify - this is an example of a Managed C++ application that uses
the .NET framework and doesn't use Critical Sections.

-cd
Nov 17 '05 #3
MPH Computers wrote:
Hi I am looking for some help
on Threading and Critical Sections

I have a main thread that controls an event

the event handler creates a new thread for carrying out the work

because the work may not be completed before the event is triggered
again
I am trying to add critical sections round the producer & consumer
parts of the work

What I am actually looking for is the VC++ syntax for creating the
thread & critical sections

It keeps asking for a second parameter for the theadstart, which is
not needed in C#

and finally the critical section return with not a class or namespace

if anybody can help I would be really grateful


Some comments:

1. Creating a new thread to handle each event is probably not the best
solution. Creating and destroying threads is expensive. If you have an
event that occurrs irregularly, or an event whose processing may sometimes
(but not too often!) take longer than the inter-event time, you're better
off creating a producer/consumer queue. Create a single worker thread that
reads events from the queue and process them, while your main thread does
whatever processing generates (or detects, receives, etc) the events.

2. To create a thread in a native C++ application (not using the .NET
framework), you should use _beginthread or _beginthreadex. Look these up on
MSDN. Both of these functions expect you to pass a pointer to a non-member
(or static member) function with the appropriate signature. Make sure you
compile with one of the Multi-Threaded options in the Code Generation
section of project properties, or these functions will not be accessible.
You can look these functions up in MSDN.

3. The CriticalSection API is very simple, consisting of only 4 or 5
functions (depending which OS version(s) you're targeting).

CRITICAL_SECTIO N - this is a struct that contains the critical section data.
Define an instance of this struct at an appropriate scope for your
application (it might be a class member or a namespace scoped variable -
just make sure it has a long enough lifetime to outlive anything that's
trying to use it).

InitializeCriti calSection - you must call this oncee for each critical
section that you use, before calling any other function.

DeleteCriticalS ection - you should call this once for each critical section
that you use, after calling any other functions. If you don't call this,
you'll be leaking resources (not really a problem if your program is going
to terminate, but it would be a problem if you're allocating CS's in a loop
and not deleting them). Note that DeleteCriticalS ection does NOT reclaim
any memory occupied by the critical section - it simply reclaims the system
resources owned by the Critical Section.

EnterCriticalSe ction - analogous to Monitor.Enter()

LeaveCriticalSe ction - analogous to Monitor.Exit().

There's also TryEnterCritica lSection, which won't block if the critical
section is already owned (and isn't supported pre windows 2000, if I recall
correctly - check MSDN).

It's common practice to wrap the CRITICAL_SECTIO N structure in a class, such
as:

struct MyCriticalSecti on : CRITICAL_SECTIO N
{
MyCriticalSecti on()
{
::InitializeCri ticalSection(th is);
}

~MyCriticalSect ion()
{
::DeleteCritica lSection(this);
}

void Enter()
{
::EnterCritical Section(this);
}

void Leave()
{
::LeaveCritical Section(this);
}
};

It's also common practice to make an "RAII" (google it) to use with the
critical section class:

class MyCSLock
{
MyCriticalSecti on& m_cs;

public:
MyCSLock(MyCrit icalSection& cs) : m_cs(cs)
{
m_cs.Enter();
}

~MyCSLock()
{
m_cs.Leave();
}
};

The lock class is used as follows

MyCriticalSecti on csQueue; // CS to protect queue

void WriteToQueue( /* whatever parameters */)
{
MyCSLock lock(csQueue);

// Write the message to the queue

// The destructor of 'lock' will automatically leave the critical section
}

void ReadFromQueue(/* whatever the parameters are */)
{

MyCSLock lock(csQueue);

// Read a message from the queue

// The destructor of 'lock' will automatically leave the critical section
}

Similar to Critical Sections, it's not uncommon to create a class to serve
as a wrapper for the Threading API. Typically something that models a subset
of the Java or .Net Thread class is implemented. I leave that as an
exercise for the reader (or do some googling - there are surely dozens of
variants out there in the wild).

Finally, MFC contains classes that encapsulate the use of threads, critical
sections, and many other aspects of native windows programming, so you might
want to look into those (although MFC does have a bit of a learning curve).

-cd

Nov 17 '05 #4
Thanks for your advice.

I think I understand

I have to create a class inside my form1class, which contains all the code
required to be included in critical section?

the consumers are required to consum only after the complete rotation of
producers has finished, so a new class for each critical section would be
required.

thanks again
"Carl Daniel [VC++ MVP]" <cp************ *************** **@mvps.org.nos pam>
wrote in message news:OT******** ********@TK2MSF TNGP09.phx.gbl. ..
Ioannis Vranos wrote:
Here is a VC++ 2003 example of a multithreading application:


Just to clarify - this is an example of a Managed C++ application that
uses the .NET framework and doesn't use Critical Sections.

-cd

Nov 17 '05 #5
"MPH Computers" <MP**********@h otmail.com> wrote in message
news:O0******** *****@tk2msftng p13.phx.gbl...
I have to create a class inside my form1class, which contains all the code
required to be included in critical section?


Despite the fact that I don't understand your question <g>, I'd like to
point out that you need to be thinking about the sections of your
application in which bad things could happen if two or more threads execute
them at the same time.

The rule of thumb is that you hold a "synchroniz e" threads (here that means
hold the critical section) for as long a period of time as is necessary, but
no longer. Those periods of time _may_ correspond to the lifetime of an
object of a class, or the time it takes to execute a method of a class, or
the time it takes to execute some instructions in a method.

Regards,
Will
Nov 17 '05 #6
"William DePalo [MVP VC++]" <wi***********@ mvps.org> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
The rule of thumb is that you hold a "synchroniz e" threads (here that
means hold the critical section) ...


Opps. Make that

The rule of thumb is that you "synchroniz e" threads (here that means
hold the critical section) ...

Regards,
Will
Nov 17 '05 #7

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

Similar topics

77
4591
by: Charles Law | last post by:
Hi guys I have a time critical process, running on a worker thread. By "time critical", I mean that certain parts of the process must be completed in a specific time frame. The time when the process starts is not especially important, but it must be complete within a small number of seconds. The operations I am performing do not take a long time (hundreds of milliseconds), but as each part of the process is complete, my worker thread...
2
4148
by: Xarky | last post by:
Hi, I am trying to learn Critical Sections. I have written a small program. Source code problem below. What the program is doing is disabling the CRTL-C signal in the critical section. My problem is that when in the Critical Section I press the CTRL-C signal more than once. As supposed nothing happens, but when critical section ends, should it give me all the CTRL-C signals pressed or just one (its giving me one)?
7
5727
by: Piotrek Stachowicz | last post by:
Hi, I need to create the situation in my system, where no more critical sections can be initialized (win2000Server). I thought about creating a simple c# application and using the Monitor class. The problem is, that the function doesn't seem tothrow any exception when it runs out of space. What can I do about it? Piotrek
13
1625
by: Hendrik van Rooyen | last post by:
Hi, I would like to do the following as one atomic operation: 1) Append an item to a list 2) Set a Boolean indicator It would be almost like getting and holding the GIL, to prevent a thread swap out between the two operations. - sort of the inverted function than for which the GIL
0
8840
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
8730
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
9215
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
9131
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,...
1
6669
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
5981
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
4484
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...
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
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.