473,407 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

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(Funtype 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(myfunA, objptrA);
thrA.start();

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

}

Thanks
Jayesh Shah.

Dec 6 '06 #1
4 6193
ja*****@gmail.com 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(false)
{
}

ScopeGuardBase(const ScopeGuardBase& other)
: m_dismissed(other.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(memFunc)
{
}

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

template <class Obj, typename MemFunc>
ScopeGuardImpl<Obj,MemFuncmakeGuard(Obj& obj,MemFunc fun)
{
return ScopeGuardImpl<Obj,MemFunc>(obj,fun);
}
Gerald

ja*****@gmail.com 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(Funtype 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(myfunA, objptrA);
thrA.start();

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

}

Thanks
Jayesh Shah.
Dec 6 '06 #3
ja*****@gmail.com 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(Funtype 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(myfunA, objptrA);
thrA.start();

B *objptrB = new B();
Thread thrB = makeThread(myfunB, 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::shared_ptr< Data the_data;

public:

template < typename FunType, typename ArgType >
Thread ( FunType fun, ArgType arg )
: the_data ( new ThreadData<FunType,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_init(&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(tid, 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_cast<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
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);...
4
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 ...
7
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...
2
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...
9
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...
8
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,...
6
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...
4
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 =...
9
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. ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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,...
0
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...

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.