473,581 Members | 3,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Thread Class

Hi All,

I am writting a Thread class with using pthread library. I have some
problem in saving thread function type and argument type. How to make
Thread class generic ?

/* This is my global Function */

template < class FunType, class ArgType>
Thread makeThread(Funt ype fun, ArgType arg)
{
Thread thr;

/* How to save Funtype and ArgType in the Thread object ?? */

return thr;
}
/* This is my thread class */
class Thread
{

void start()
{
/* pthread_create here to create a new thread */
}

};
class A
{
static void myfunA(A *ptr)
{
/* This function will run as a new thread); */
}
};

class B
{
static void myfunB(B *ptr)
{
}
}

main()
{
A *objptrA = new A();
Thread thrA = makeThread(myfu nA, objptrA);
thrA.start();

B *objptrB = new B();
Thread thrB = makeThread(myfu nB, objptrB);
thrB.start();

}

Thanks
Jayesh Shah.

Dec 6 '06 #1
4 6210
ja*****@gmail.c om wrote:
Hi All,

I am writting a Thread class with using pthread library. I have some
problem in saving thread function type and argument type. How to make
Thread class generic ?

There are quite a few examples of thread classes.

- Austria C++ (shameless plug)
- boost
- ACE

Then there are some docs on the standardization efforts:

http://www.open-std.org/jtc1/sc22/wg...006/n2094.html
http://www.artima.com/cppsource/threads_meeting.html

That should keep you fed with ideas for quite a while.
Dec 6 '06 #2

See following example, its's similar

class ScopeGuardBase
{
public:
void dismiss() const throw()
{
m_dismissed = true;
}

protected:
ScopeGuardBase( ) : m_dismissed(fal se)
{
}

ScopeGuardBase( const ScopeGuardBase& other)
: m_dismissed(oth er.m_dismissed)
{
other.dismiss() ;
}

~ScopeGuardBase ()
{
}

mutable bool m_dismissed;

private:
// Disable assignment
ScopeGuardBase& operator=(const ScopeGuardBase& );
};

typedef const ScopeGuardBase& ScopeGuard;

template <class Obj, typename MemFunc>
class ScopeGuardImpl: public ScopeGuardBase
{
public:
ScopeGuardImpl( Obj& obj, MemFunc memFunc)
: m_obj(obj), m_memFunc(memFu nc)
{
}

~ScopeGuardImpl ()
{
if (!m_dismissed)
{
(m_obj.*m_memFu nc)();
}
}
private:
Obj& m_obj;
MemFunc m_memFunc;
};

template <class Obj, typename MemFunc>
ScopeGuardImpl< Obj,MemFuncmake Guard(Obj& obj,MemFunc fun)
{
return ScopeGuardImpl< Obj,MemFunc>(ob j,fun);
}
Gerald

ja*****@gmail.c om wrote:
Hi All,

I am writting a Thread class with using pthread library. I have some
problem in saving thread function type and argument type. How to make
Thread class generic ?

/* This is my global Function */

template < class FunType, class ArgType>
Thread makeThread(Funt ype fun, ArgType arg)
{
Thread thr;

/* How to save Funtype and ArgType in the Thread object ?? */

return thr;
}
/* This is my thread class */
class Thread
{

void start()
{
/* pthread_create here to create a new thread */
}

};
class A
{
static void myfunA(A *ptr)
{
/* This function will run as a new thread); */
}
};

class B
{
static void myfunB(B *ptr)
{
}
}

main()
{
A *objptrA = new A();
Thread thrA = makeThread(myfu nA, objptrA);
thrA.start();

B *objptrB = new B();
Thread thrB = makeThread(myfu nB, objptrB);
thrB.start();

}

Thanks
Jayesh Shah.
Dec 6 '06 #3
ja*****@gmail.c om wrote:
Hi All,

I am writting a Thread class with using pthread library. I have some
problem in saving thread function type and argument type. How to make
Thread class generic ?

/* This is my global Function */

template < class FunType, class ArgType>
Thread makeThread(Funt ype fun, ArgType arg)
{
Thread thr;

/* How to save Funtype and ArgType in the Thread object ?? */

return thr;
}
/* This is my thread class */
class Thread
{

void start()
{
/* pthread_create here to create a new thread */
}

};
class A
{
static void myfunA(A *ptr)
{
/* This function will run as a new thread); */
}
};

class B
{
static void myfunB(B *ptr)
{
}
}

main()
{
A *objptrA = new A();
Thread thrA = makeThread(myfu nA, objptrA);
thrA.start();

B *objptrB = new B();
Thread thrB = makeThread(myfu nB, objptrB);
thrB.start();

}
What about:

#include <tr1/memory// shared_ptr

class Thread {

struct Data {

virtual ~Data ( void ) {}

virtual
void start ( void ) = 0;
};

template < typename FunType, typename ArgType >
struct ThreadData : public Data {

FunType the_fun;
ArgType the_arg;

ThreadData ( FunType fun, ArgType arg )
: the_fun ( fun )
, the_arg ( arg )
{}

void start ( void ) {
// do whatever it takes to start the thread
}

};

std::tr1::share d_ptr< Data the_data;

public:

template < typename FunType, typename ArgType >
Thread ( FunType fun, ArgType arg )
: the_data ( new ThreadData<FunT ype,ArgType>( fun, arg ) )
{}

void start ( void ) {
the_data->start();
}

}; // Thread
struct A {
static void myfunA(A *ptr)
{
/* This function will run as a new thread); */
}
};

struct B {
static void myfunB(B *ptr)
{
}
};

int main()
{
A *objptrA = new A();
Thread thrA (A::myfunA, objptrA);
thrA.start();

B *objptrB = new B();
Thread thrB (B::myfunB, objptrB);
thrB.start();

}

Best

Kai-Uwe Bux
Dec 6 '06 #4
TvN
Hi All,
I am writting a Thread class with using pthread library. I have some
problem in saving thread function type and argument type. How to make
Thread class generic ?
Firstly take a look at boost::threads - it is pretty simple and small
;)

If you want to create another class for pthread do not forgot the next:
thread function (function passed to pthread_create) must have C
linkage, so it cannot be class/structure member.
Do not forget that it returns void* and takes void* as parameter, so
you should be careful with type conversion;)

As example it could be code below. Do not forget add correct error
handling. I hope it will be helpful ;)
//! Abstract class for thread execution.
class worker
{
public:
//! This method called in thread
virtual void execute() throw() = 0;
//! This method called when thread is canceled
virtual void cancel() throw() = 0;
//! this method called if error occur in thread
virtual void err_handle() throw()= 0;
//! Destructor.
virtual ~worker()
{}
};
extern "C" void* executor(void* b);

//! Main class for thread operations.
class thread
{
friend void* executor(void* b);
//! Main thread function.
//! \arg thread data.
//! \return thread result.
private:
//! disabled constructor
thread();
//! disabled constructor
thread(const thread& t);
//! disabled operator
thread& operator=(const thread& t);

public:
//! Constructor.
/*! Takes a pointer to worker object, and use it as
* thread function.
* \note In this case default thread attribute will be used.
*/
thread(worker* w)
: funct(w)
{
int r;
if ((r = pthread_attr_in it(&attr)) != 0)
{
throw r;
}
}
//! Constructor.
//! \arg worker* w - worker object.
//! \arg const pthread_attr_t &attr_ - thread attribute.
thread(worker* w, const pthread_attr_t &attr_)
: attr(attr_), funct(w)
{ }
//! Destructor.
/*! Firstly thread is detached, and then it canceled.
* This approach is used because POSIX does not have other
approach
* to destroy other thread.
*/
virtual ~thread()
{
pthread_detach( tid);
pthread_cancel( tid);
}
//! Returns thread identifier (TID)
pthread_t getTID() const
{
return tid;
}
//! Returns TID of the thread in which this method called.
static pthread_t self()
{
return pthread_self();
}
//! Create new thread and returns it's TID.
//! \note In case of error exception with error code will be thrown

pthread_t create()
{
int r = pthread_create( &tid, &attr, executor, this);
if (r != 0)
{
throw r;
}
return tid;
}
//! Joins the thread. Thsi thread should be joinable.
//! \note In case of error exception with error code will be thrown

void join()
{
int r;
if ((r = pthread_join(ti d, NULL)) != 0)
{
throw r;
}
}
//! Detaches the thread.
//! \note In case of error exception with error code will be thrown

void detach()
{
int r;
if ((r = pthread_detach( tid)) != 0)
{
throw r;
}
}
//! Detaches the thread which TID is tid_
//! \note In case of error exception with error code will be thrown

static void detach(pthread_ t tid_)
{
int r;
if ((r = pthread_detach( tid_)) != 0)
{
throw r;
}
}
//! Cancels the thread.
//! \note In case of error exception with error code will be thrown

void cancel()
{
int r;
if ((r = pthread_cancel( tid)) != 0)
{
throw r;
}
}
//! Cancels the thread which TID is tid_.
//! \note In case of error exception with error code will be thrown

static void cancel(pthread_ t tid_)
{
int r;
if ((r = pthread_cancel( tid_)) != 0)
{
throw r;
}
}
private:
pthread_t tid; //!< Thread's ID
pthread_attr_t attr;//!< Thread's attribute

worker* funct;//!< Thread's class function.
};
void* executor(void* b)
{
try{
thread *thr = reinterpret_cas t<thread*>(b);
if (thr != NULL)
{
try
{
thr->funct->execute();
}catch(...)
{
thr->funct->err_handle() ;
}
}
}catch(...)
{}
return NULL;
}

Dec 7 '06 #5

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

Similar topics

6
23721
by: Tomaz Koritnik | last post by:
I have a class that runs one of it's method in another thread. I use Thread object to do this and inside ThreadMethod I have an infinite loop: While (true) { // do something Thread.Sleep(100); } The problem is that I don't know how to terminate the thread when my class
4
1546
by: Daylor | last post by:
hi. i have multi thread application in vb.net is there a way NET support, so i can mark the class , to be access only for 1 thread each time ? if there is , small sytax sample will help //what i need to add , so only 1 thread per time can access this class in MultiThread app.
7
2678
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 a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
2
1676
by: MIke Brown | last post by:
Hello all, I've been searching for a solution on google for a problem related to creating events from a worker thread, with no luck.. Basically, the problem is when my events are caught by a UI using my class, they get the usual "Control 'blah' accessed from a thread other than the thread it was created on.". I understand that of course,...
9
3260
by: esakal | last post by:
Hello, I'm programming an application based on CAB infrastructure in the client side (c# .net 2005) Since my application must be sequencally, i wrote all the code in the UI thread. my problem occurs when i try to show a progress bar. The screen freezes. I know i'm not the first one to ask about it. but i'm looking
8
1687
by: Carl Heller | last post by:
If I'm creating a class to do some work that I want threaded out, where's the best location to call ThreadStart? Or does it depend on the nature of the work? a. Call it outside the class, giving it the starting method of the class? b. Have the class create the thread itself? ie: x = new WorkerClass(); ioThread = new Thread(new...
6
5109
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to...
4
1413
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 = "#TRADE, D1410-123456, BUY, 1, ESM7, DAY, LIMIT, 1490.00, , , 0, 0, 0, 0, 0, links |52994/25/2007 10:47:17 AM !A", when I trigger to create many...
9
3245
by: Pubs | last post by:
Hi all, I want to call a function with some intial parameters with in a thread. At the end of the function execution it should return a value to the caller. Caller is outside the thread. Example function test (int a, int b);
0
7809
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...
0
8312
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...
1
7920
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...
1
5685
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...
0
5366
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...
0
3809
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...
0
3835
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1413
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1147
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...

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.