473,789 Members | 2,346 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Question on C++ Thread Class and inheritance/polymorphism with POSIX pthread

FWIW, here is a quick example (in the form of a fully compliable program
with error checking omitted) of how I use POSIX threads within a C++
environment:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(vo id*);
virtual void on_thread_entry () = 0;

public:
virtual ~thread_base() = 0;

void thread_run() {
pthread_create( &m_tid, NULL, thread_entry, this);
}

void thread_join() {
pthread_join(m_ tid, NULL);
}
};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
reinterpret_cas t<thread_base*> (state)->on_thread_entr y();
return 0;
}

template<typena me T>
struct thread : public T {
thread() : T() {
this->thread_run() ;
}

~thread() {
this->thread_join( );
}

template<typena me T_p1>
thread(T_p1 p1) : T(p1) {
this->thread_run() ;
}

template<typena me T_p1, typename T_p2>
thread(T_p1 p1, T_p2 p2) : T(p1, p2) {
this->thread_run() ;
}

// [and on and on for for params...]
};


/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <string>
#include <cstdio>
class worker : public thread_base {
std::string const m_name;

void on_thread_entry () {
std::printf("(% p)->worker(%s)::on _thread_entry() \n",
(void*)this, m_name.c_str()) ;
}

public:
worker(std::str ing const& name)
: m_name(name) {
std::printf("(% p)->worker(%s)::my _thread()\n",
(void*)this, m_name.c_str()) ;
}

~worker() {
std::printf("(% p)->worker(%s)::~m y_thread()\n",
(void*)this, m_name.c_str()) ;
}
};
int main(void) {
{
thread<workerwo rkers[] = {
"Chris",
"John",
"Jane",
"Steve",
"Richard",
"Lisa"
};

worker another_worker( "Jeff");
another_worker. thread_run();
another_worker. thread_join();
}

std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
std::fflush(std out);
std::getchar();
return 0;
}
_______________ _______________ _______________ _______________ _____


IMVHO, this is very straight forward and works well. In fact, I think I like
it better than the Boost method... Humm... Well, what do you all think about
the design? Is it crap?

Oct 28 '08 #1
1 3595
On Oct 29, 12:07*am, "Chris M. Thomasson" <n...@spam.inva lidwrote:
FWIW, here is a quick example (in the form of a fully compliable program
with error checking omitted) of how I use POSIX threads within a C++
environment:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>

extern "C" void* thread_entry(vo id*);

class thread_base {
* pthread_t m_tid;
* friend void* thread_entry(vo id*);
* virtual void on_thread_entry () = 0;

public:
* virtual ~thread_base() = 0;

* void thread_run() {
* * pthread_create( &m_tid, NULL, thread_entry, this);
* }

* void thread_join() {
* * pthread_join(m_ tid, NULL);
* }

};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
* reinterpret_cas t<thread_base*> (state)->on_thread_entr y();
* return 0;

}

template<typena me T>
struct thread : public T {
* thread() : T() {
* * this->thread_run() ;
* }

* ~thread() {
* * this->thread_join( );
* }

* template<typena me T_p1>
* thread(T_p1 p1) : T(p1) {
* * this->thread_run() ;
* }

* template<typena me T_p1, typename T_p2>
* thread(T_p1 p1, T_p2 p2) : T(p1, p2) {
* * this->thread_run() ;
* }

* // [and on and on for for params...]

};

/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <string>
#include <cstdio>

class worker : public thread_base {
* std::string const m_name;

* void on_thread_entry () {
* * std::printf("(% p)->worker(%s)::on _thread_entry() \n",
* * * (void*)this, m_name.c_str()) ;
* }

public:
* worker(std::str ing const& name)
* * : m_name(name) {
* * std::printf("(% p)->worker(%s)::my _thread()\n",
* * * (void*)this, m_name.c_str()) ;
* }

* ~worker() {
* * std::printf("(% p)->worker(%s)::~m y_thread()\n",
* * *(void*)this, m_name.c_str()) ;
* }

};

int main(void) {
* {
* * thread<workerwo rkers[] = {
* * * "Chris",
* * * "John",
* * * "Jane",
* * * "Steve",
* * * "Richard",
* * * "Lisa"
* * };

* * worker another_worker( "Jeff");
* * another_worker. thread_run();
* * another_worker. thread_join();
* }

* std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
* std::fflush(std out);
* std::getchar();
* return 0;}

_______________ _______________ _______________ _______________ _____

IMVHO, this is very straight forward and works well. In fact, I think I like
it better than the Boost method... Humm... Well, what do you all think about
the design? Is it crap?
The active object concept is much better than the Boost thread and I
have suggested it earlier that the C++0x committee should consider
this pattern, i.e. active object, as a high level wrapper construction
next to their high level wrapper wait/2 on the condition variable:

<quote from="
http://groups.google.com/group/comp....80468d988c4feb
">
I do think it has advantages over Boost's method. One such advantage
is the RAII nature of it.

Furthermore, I think it should be taken in into the C++0x standard on
the similar grounds as they provide higher level condition variable
wait API as well:

<quote>
template <class Predicate>
void wait(unique_loc k<mutex>& lock, Predicate pred);
Effects:
As if:
while (!pred())
wait(lock);
</quote>
http://www.open-std.org/jtc1/sc22/wg...008/n2497.html
</quote>

Another remark: Why do you not keep to the terminology we have come up
with earlier? It is for an active object and not for any plain thread.
See:

"What's the connection between objects and threads?"
http://groups.google.com/group/comp....d6d69cae17fee7

What is the difference between:

worker another_worker( "XY");
another_worker. thread_run();
another_worker. thread_join();

and

ActiveObject<wo rkeranother_wor ker("XY");

Well, the difference is that the wrapper takes care of the low level
details of starting and stopping the thread. As a bonus, it is
impossible to miss to join the thread. In other frameworks they tend
to call it the fork-join style.

So, you might consider this patch for clarity:

34,35c34,35
< struct ActiveObject : public T {
< ActiveObject() : T() {
---
struct thread : public T {
thread() : T() {
39c39
< ~ActiveObject() {
---
~thread() {
44c44
< ActiveObject(T_ p1 p1) : T(p1) {
---
thread(T_p1 p1) : T(p1) {
49c49
< ActiveObject(T_ p1 p1, T_p2 p2) : T(p1, p2) {
---
thread(T_p1 p1, T_p2 p2) : T(p1, p2) {
86c86
< ActiveObject<wo rkerworkers[] = {
---
thread<workerwo rkers[] = {
I believe that the program will be clearer and more readable if you
keep to the terminology that reflects the active object. It is not a
good idea to overload the term `thread' since it will just cause some
more confusion.

Best Regards,
Szabolcs
Oct 29 '08 #2

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

Similar topics

0
1380
by: Tseng, Ling-hua | last post by:
As the comments of the following C++ code, I got the ambiguous error in the specialized class " PThreadTimer<void *(*)(void *)> ". I performed the virtual inheritance mechanism on its base classes : "PThreadBase" and "PThread<> ", and then the derived template class "PThreadTimer< >" could pass the compilation without any ambiguous errors. But it's occured in the specialized class " PThreadTimer<void *(*)(void *)> ". Why are the ambiguous...
9
2239
by: David A. Osborn | last post by:
I have a set of classes that each have an enumeration in them, and based on dynamic input I need to access a different enumeration. For example Three classes Class_A, Class_B, and Class_C that all have a different enumeration in them called Properties. I want to basically have a variable The_Class that I can dynamically point to either Class_A, Class_B, or Class_C and then do The_Class.properties to get the correct enumeration. How...
0
993
by: hecklar | last post by:
I'm having a problem with threading (permissions?) in a VB.net Windows application (background service). I'm trying to write an application that processes files, launching a new thread for each file that is dropped into a certain folder. Now, the application works like a charm on my Win2000 machine, but when I moved it to the Win2000 server, where it will eventually need to run, it fails. One of the processes that is run on the file...
39
1879
by: elnanni | last post by:
I've a problem in the use of threads, they don't work as i want them to. Here's the code, the problem is that if i uncomment the //pthread_join(thread_ID, NULL);, the main program stops until the spawned thread is finished, but that's not the intended way, because i need that the opc variable change only when the user pushes a key, i think it has something to do with the pthread_attr_set(atribute) options, but i didn't get with the answer...
5
4123
by: Martin Jørgensen | last post by:
Hi, Consider this code: --- beginning of code --- #include <iostream> using namespace std; class Child{ public:
4
6221
by: jayesah | last post by:
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)
23
5716
by: Boltar | last post by:
Hi I'm writing a threading class using posix threads on unix with each thread being run by an object instance. One thing I'm not sure about is , if I do the following: myclass::~myclass() { : : do stuff
1
1819
by: Ian Collins | last post by:
Chris M. Thomasson wrote: Why bother with all that nonsense when there is a standard solution? -- Ian Collins
0
1813
by: JoelKatz | last post by:
On Oct 27, 10:55 am, alexroat <alexr...@gmail.comwrote: Really? What do you get with this code: #include <stdio.h> #include <pthread.h> class Thread {
0
9502
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
10185
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
10132
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
9974
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9006
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
6753
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
5408
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...
0
5544
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2901
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.