Search
Relevant Links
Top 10 Articles
Faster Windows 7 - How To Make Windows 7 Faster Easily And Quickly
Does your windows 7 run too slow?
Faster Windows 7 - How To Make Windows 7 Faster Easily And Quickly
Windows 7 Slow? Speed Up Slowing Windows 7 With These Tips
Windows 7 Slow? Speed Up Slowing Windows 7 With These Tips
Windows 7 Slow? Speed Up Slowing Windows 7 With These Tips
Different Types Of Computer Memory
Different Types of Computer Memory
Different Types Of Computer Memory
Successful Blogging Tips To Make Money Online
Successful Blogging Tips to Make Money Online
Successful Blogging Tips To Make Money Online
Computer Hardware - Learn How To Fix Your Computer
Computer hardware has changed a lot over the past 15 years and most computers used to be large and heavy and were very difficult to use because they did not have an operating system
Computer Hardware - Learn How To Fix Your Computer
Discount Computer Accessories
An accessory is an additional item for a product that helps in contributing to its utility
Discount Computer Accessories
Understand Viruses
Every computer user should be at least aware, if not conscious, of the now prevalent computer viruses
Understand Viruses
Evaluation Microsoft Windows 7
After the rather lackluster launch of Windows Vista, Microsoft is ready with another operating system that could succeed Windows XP in the true sense.
Evaluation Microsoft Windows 7
Satellite Tv On PC & Mobile Tv Pro
Instantly Turn your Computer into a Super TV. Does it really work?
Satellite Tv On PC & Mobile Tv Pro
Computer Firewalls
A firewall is a computer software that provides protection from hacking attempts from the Internet
Computer Firewalls
Categories
Related Links

 

ComputerInfoWeb.com

ComputerInfoWeb.com offers tips on computers, notebooks, repairs, Shopping, Software, Security, Computer Rental , Computer Shopping, Computer Programming, Computer Networking, Maintenance, Hardware, Internet, Game, Electronics and more.

Computer Programming

Computer Programming : CPlusPlus Multi-threading And Thread Synchronization On Win32

 

Introduction


Have you ever found multi-threading and thread

synchronization difficult tasks in Win32? Then try these classes. Here

I provide a small code library that will give you tools for creating

multi-threaded applications in the C++ way, with out using MFC. If you

have done multi-threading in Java and got fed up with the thread

classes in MFC, you have come to the right place. Enough talking, I

will take you right away through a step-by-step tutorial on using these

classes.



Background



You should be familiar with OOPs. You should also be familiar

with terms like virtual functions, overriding, namespaces, exceptions

etc. But you need not be a C++ guru.



Using the code



First, I will give you the list of header files you should include in the CPP file that use my thread classes:

#include 
using namespace std;

#include "ou_thread.h"
using namespace openutils;


The next step is to create a customized Thread class from the base Thread class that you find in ou_thread.h:

class MyThread : public Thread {
private:
int m_nCount;
public:
MyThread(int n,const char* nm) {
Thread::setName(nm);
m_nCount = n;
}
void run() {
for(int i=0;i
cout << getName().c_str() << ":" << i << endl;
}
}
};


If you have done thread programming in Java, the above class will look familiar. First we have inherited publicly from the Thread class and then we gave our own implementation to the run() function. The MyThread class we just created has a private integer variable which is used by the run() function to print out the thread's name that much time. The setName() and getName() functions are derived from the base class.



Now let us create a main() function to test the MyThread class:

int main() {
Thread *t1 = new MyThread(15,"Thread 01");
Thread *t2 = new MyThread(10,"Thread 02");
try {
t1->start();
t2->start();
t1->stop();
t2->stop();
}catch(ThreadException ex) {
printf("%s\n",ex.getMessage().c_str());
}
delete t1;
delete t2;
return 0;


Here we created two thread pointers pointing to MyThread objects.



The MyThread constructor takes two

arguments, value of the counter variable and the thread name. Then we

start both these threads by calling the start() function, which in turn calls our implementation of run(). If the low-level thread creation was not successful, then the try-catch block will handle that problem gracefully.



When you run this program, you will get output much like the following:

ThreThread 02:0
Thread 02:1
Thread 02ad 01:1
Thread 01:2
Thread 01:3
Thr:2
Thread 02:3
Thread 02:4
Thread 0ead 01:4
Thread 01:5
Thread 01:6
Th2:5
Thread 02:6
Thread 02:7
Thread read 01:7
Thread 01:8
Thread 01:9
T02:8


Thread synchronization



You can see that thread2 is executing the run()

function before thread1 has finished and both threads execute together

to produce a confusing result. This can be more serious if both threads

are accessing a critical resource like a database file at the same

time. This problem can be solved by using a Mutex object.



A Mutex is a synchronization object that allows one

thread mutually exclusive access to a resource. We can create a mutex

using the Mutex class and hand over its ownership

to the first thread. The next thread can be made to "wait" until the

first thread "releases" the ownership of that object. Let us see how

this can be achieved.



First include the following declaration to the main() function just before calling t1->start();

Mutex m("MyMutex");


This will create a mutex object identified by the name MyMutex. We can use this object in the run() function to control access to shared code. Modify the run() function in MyThread class to include calls to wait() and release() functions:

void run() {
wait("MyMutex");
for(int i=0;i
cout << getName().c_str() << ":" << i << endl;
}
release("MyMutex");
}


Please keep in mind that mutex names are case sensitive. If the mutex is not found, then wait() and release() functions will throw a ThreadException. Now recompile and run the program. You will see the following output:

Thread 01:1
Thread 01:2
Thread 01:3
Thread 01:4
Thread 01:5
Thread 01:6
Thread 01:7
Thread 01:8
Thread 01:9
Thread 01:10
Thread 01:11
Thread 01:12
Thread 01:13
Thread 01:14
Thread 02:0
Thread 02:1
Thread 02:2
Thread 02:3
Thread 02:4
Thread 02:5
Thread 02:6
Thread 02:7
Thread 02:8
Thread 02:9


You can see how thread2 waits until thread1 is finished, to

produce the desired output. Using mutexes has their own overhead and

tends to slow down everything. So use them when only one thread at a

time should be allowed to modify data or some other controlled resource.



If synchronized by a mutex, it is important to call stop() on all threads in the same order start() was called on them. If no mutex was used, you can avoid calling stop() on threads.



Call the release() function of mutex after the calls to stop() functions of the thread objects.

t1->stop();
t2->stop();
m.release();


Thread priority



Every thread has a base priority level determined by the

thread's priority value and the priority class of its process. The

system uses the base priority level of all executable threads to

determine which thread gets the next slice of CPU time. Threads are

scheduled in a round-robin fashion at each priority level, and only

when there are no executable threads at a higher level does scheduling

of threads at a lower level take place.



The setPriority() function enables

setting the base priority level of a thread relative to the priority

class of its process. This function can take any of the following

values as its only argument:

Priority ValueMeaning
Thread::P_ABOVE_NORMALIndicates 1 point above normal priority for the priority class.
Thread::P_BELOW_NORMALIndicates 1 point below normal priority for the priority class.
Thread::P_HIGHESTIndicates 2 points above normal priority for the priority class.
Thread::P_IDLEKeeps this thread idle.
Thread::P_LOWESTIndicates 2 points below normal priority for the priority class.
Thread::P_NORMALIndicates normal priority for the priority class.
Thread::P_CRITICALPuts the thread in the highest possible priority.


For example, the following code puts thread1 in a high priority:

t1->setPriority(Thread::P_HIGHEST);


By default, a thread is created with the P_NORMAL priority.


Other Relevant Articles from this Category:
Javascript
CPlusPlus Multi-threading And Thread Synchronization On Win32
Private Vs Protected OOP
Visual Basic.NET
Visual Basic
PHP
Java

More Categories:
Notebook Computer  
Computer Training  
Desktop Computer  
Computer Sale  
Computer Software  
Computer Repair  
Computer Store  
Computer Game  
Computer Hardware  
Computer Electronics  
Computer Security  
Computer Programming  
Computer Memory  
Computer Science  
Used Computer  
Computer Networking  
Computer Rental  
Computer Accessory  
Computer Algorithm  
Computer Shopping  
Computer Maintenance  
Computer Internet  
Outsourcing  
Windows 7