I have a such a requirement that:-
1) There are two class, say Wrapper and Wrapper2.
2) Wrapper2 contains reference object of class Wrapper.
3) A thread will write data to a variable of class Wrapper which should be essentially be calling a member function of Wrapper.
4) Another thread can read and write data to class member of Wrapper and this thread essentially be called through Wrapper2.
Based on some answers on older question on Stackoverflow, i created an example code to check why my production code is failing and i am not able to figure out the problem. As soon as thread2 is created it receives SIGSEG signals. Code is below:-
#include <thread>
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include <wait.h>
#include <string.h>
pthread_mutex_t mt1;
void thread_signal(int signum)
{
pthread_exit(0);
}
void sig_func(int sig)
{
write(1, "Caught signal 11\n", 17);
std::cout<<"Caught signal :"<<sig<<std::endl;
signal(SIGSEGV,sig_func);
thread_signal(sig);
}
class Wrapper {
public:
Wrapper():i(10)
{
std::cout<<"Wrapper Constructor Called. "<<this<<" \n";
}
~Wrapper()
{
std::cout<<"Wrapper Destructor Called. "<<this<<"\n";
}
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
void setI(int i)
{
pthread_mutex_lock(&mt1);
this->i=i;
std::cout<<"set: "<< this->i<<std::endl;
pthread_mutex_unlock(&mt1);
}
int getI()
{
pthread_mutex_lock(&mt1);
std::cout<<"get: "<< this->i<<std::endl;
pthread_mutex_unlock(&mt1);
return 0;
}
int i;
};
class Wrapper2
{
public:
Wrapper2(Wrapper & wp):wp2(wp)
{
std::cout<<"Wrapper2 Constructor Called. "<<this<<" \n";
}
~Wrapper2()
{
std::cout<<"Wrapper2 Destructor Called. "<<this<<" \n";
}
Wrapper & wp2;
};
struct ThreadWrapper {
Wrapper & wr1;
Wrapper2 & wr2;
ThreadWrapper( Wrapper & wr1,Wrapper2& wr2):
wr1(wr1),wr2(wr2)
{
}
};
extern "C" void* wrapper1Fun ( void* wr1)
{
std::auto_ptr< Wrapper > wrp1 ( static_cast< Wrapper* >( wr1 ) );
std::cout<<"Thread 1 created. \n";
while(1)
{
wrp1->setI(rand()%100);
usleep(50);
}
return 0;
}
extern "C" void* wrapper2Fun ( void* wr2)
{
std::auto_ptr< Wrapper2 > wrp2 ( static_cast< Wrapper2* >( wr2 ) );
std::cout<<"Thread 2 created. \n";
while(1)
{
wrp2->wp2.getI();
usleep(50);
}
return 0;
}
int main(int argc, char **argv) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = thread_signal;
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, 0);
bool mainRunning= true;
Wrapper w;
Wrapper2 w1(w);
sleep(1);
ThreadWrapper * myWrap = new ThreadWrapper(w,w1);
sleep(1);
pthread_t pt1;
pthread_t pt2;
pthread_attr_t attr;
signal(SIGSEGV,sig_func); // Register signal handler before going multithread
pthread_attr_init(&attr);
int i = pthread_create(&pt1, NULL,wrapper1Fun, myWrap);
std::cout<<"First thread status "<<i<<std::endl;
sleep(1);
int j = pthread_create(&pt2, &attr,wrapper2Fun, myWrap);
std::cout<<"Second thread status "<<j<<std::endl;
sleep(1);
while(1);
fprintf(stderr, "kill thread\n");
//pthread_kill(pt1, SIGTERM);
fprintf(stderr, "join thread\n");
pthread_join(pt1, NULL);
pthread_join(pt1, NULL);
return 0;
}
wrapper1Fun expects to be passed a pointer to a Wrapper, and wrapper2Fun expects to be passed a pointer to a Wraper2. But you're actually passing a pointer to a ThreadWrapper to each, which is a completely different type, so it goes wrong.
The use of void * and casts prevents the compiler from pointing out your type error. I would suggest using a type safe C++ threading library rather than raw pthread. Boost has one, as does the standard library from C++11.
Also your use of auto_ptr is questionable at best. It's deprecated, easy to get wrong, and a poor way of expressing ownership - prefer unique_ptr or shared_ptr.
Here you construct two auto_ptr values owning the same pointer, so it will be freed twice, which is undefined behaviour.
In any case there's no obvious reason to put any of these objects on the heap. If you do, you need to decide where the ownership of the memory resides.
Related
I have the follwing code that gets core dumped error. Each C instance creates their own thread then runs. I guess there is something wrong with static function and class argument "count". When I comment out the code that prints it, no fault occurs..
#include <iostream>
#include <pthread.h>
using namespace std;
class C {
public:
int count;
C(int c_): count(c_){}
public:
void *hello(void)
{
std::cout << "Hello, world!" <<std::endl;
std::cout<<count; // bug here!!!
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
void run() {
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, NULL);
}
};
int main() {
C c(2);
c.run();
C c2(4);
c2.run();
while(true);
return 0;
}
Decided to write an answer. You were calling hello_helper with a context of NULL based on how you were creating your thread. C++ fully allows you to call member functions on null pointers, and no error occurs unless a member element is accessed.
In your case, by adding the line to print count. You are now accessing a member variable on a null pointer, which is a big no-no.
Here's an example of what you were getting away with:
#include <iostream>
class Rebel
{
public:
void speak()
{
std::cout << "I DO WHAT I WANT!" << std::endl;
}
};
int main()
{
void * bad_bad_ptr = NULL;
((Rebel*)bad_bad_ptr)->speak();
}
Output:
I DO WHAT I WANT!
By modifying your pthread_create call to pass the this pointer (i.e. pthread_create(&t, NULL, &C::hello_helper, this);, you now have a valid instance to access member variables on.
I solved the problem by passing this pointer instead off NULL while creating threads. I guess os created same thread twice int the former case ?
I'm having troubles with creation of the function, that should handle new thread. When I create it outside of the class, everything works allright, but when I want to create it inside a class, I can't realize, how to call it.
I call the function with:
pthread_t thread;
pthread_create(&thread, NULL,
sendMessage, (void *) fd);
and the function itself looks like this:
void * sendMessage(void *threadid) {
string message;
const char * c;
char buffer[200];
int fd = (long) threadid;
while (true) {
cin >> message;
if (message == "exit") {
break;
}
c = message.c_str();
strncpy(buffer, c, sizeof ( buffer));
send(fd, buffer, strlen(buffer), 0);
}
}
but when I declare it within a class e.g. void * Client::sendMessage(void *threadid) , I can't even build it because I get main.cpp:90:37: error: argument of type ‘void* (Client::)(void*)’ does not match ‘void* (*)(void*)’ Does anybody have any idea, what can cause it and how to fix it?
Just a quick demonstration of how std::thread can quickly make all your woes disappear (by seemlessly integrating with std::bind style invocation):
#include <string>
#include <thread>
#include <memory>
void some_function(int i, std::string bla)
{
}
struct some_class
{
void some_member_function(double x) const
{
}
};
int main()
{
std::thread t1(&some_function, 42, "the answer");
std::thread t2;
{
some_class instance;
t2 = std::thread(&some_class::some_member_function,
std::ref(instance),
3.14159);
t2.join(); // need to join before `instance` goes out of scope
}
{
auto managed = std::make_shared<some_class>();
t2 = std::thread([managed]()
{
managed->some_member_function(3.14159);
});
// `managed` lives on
}
if (t1.joinable()) t1.join();
if (t2.joinable()) t2.join();
}
I am very new to C++.
I have a class, and I want to create a thread inside a class's function. And that thread(function) will call and access the class function and variable as well.
At the beginning I tried to use Pthread, but only work outside a class, if I want to access the class function/variable I got an out of scope error.
I take a look at Boost/thread but it is not desirable because of I don't want to add any other library to my files(for other reason).
I did some research and cannot find any useful answers.
Please give some examples to guide me. Thank you so much!
Attempt using pthread(but I dont know how to deal with the situation I stated above):
#include <pthread.h>
void* print(void* data)
{
std::cout << *((std::string*)data) << "\n";
return NULL; // We could return data here if we wanted to
}
int main()
{
std::string message = "Hello, pthreads!";
pthread_t threadHandle;
pthread_create(&threadHandle, NULL, &print, &message);
// Wait for the thread to finish, then exit
pthread_join(threadHandle, NULL);
return 0;
}
You can pass a static member function to a pthread, and an instance of an object as its argument. The idiom goes something like this:
class Parallel
{
private:
pthread_t thread;
static void * staticEntryPoint(void * c);
void entryPoint();
public:
void start();
};
void Parallel::start()
{
pthread_create(&thread, NULL, Parallel::staticEntryPoint, this);
}
void * Parallel::staticEntryPoint(void * c)
{
((Parallel *) c)->entryPoint();
return NULL;
}
void Parallel::entryPoint()
{
// thread body
}
This is a pthread example. You can probably adapt it to use a std::thread without much difficulty.
#include <thread>
#include <string>
#include <iostream>
class Class
{
public:
Class(const std::string& s) : m_data(s) { }
~Class() { m_thread.join(); }
void runThread() { m_thread = std::thread(&Class::print, this); }
private:
std::string m_data;
std::thread m_thread;
void print() const { std::cout << m_data << '\n'; }
};
int main()
{
Class c("Hello, world!");
c.runThread();
}
I am having problems calling my functions from my main program.
These functions HAVE to be in my class.
How do I access them from my int main()?
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <semaphore.h>
#include <synch.h>
using namespace std;
class myCountingSemaphoreUsingBinarySemaphore {
public:
void waitSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_lock(*thread);// Makes value 1 (Not Available)
}
void signalSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_unlock(*thread); // Makes value 0 (Available)
}
void deleteSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_destroy(*thread);// Deletes
}
};
int readerCount;
int database = (rand() / 100); // Number less than 1000
void reader_writer(void);
int main(int argc, char *argv[])
{
myCountingSemaphoreUsingBinarySemaphore obj;
pthread_mutex_t mutex1;
pthread_mutex_t wrt;
pthread_create( &mutex1, NULL, reader_writer, void);
pthread_create( &wrt, NULL, reader_writer, void);
//----------------------READER------------------------//
do{
cout << "Database Before Read = " << database << endl;
obj.waitSemaphore(mutex1);//lock
readerCount++;
if (readerCount == 1)
{
obj.waitSemaphore(wrt);//lock
obj.signalSemaphore(mutex1);//unlock
//reading is preformed
obj.waitSemaphore(mutex1); // lock
readerCount--;
}
if(readerCount == 0)
{
obj.signalSemaphore(wrt);//unlock
obj.signalSemaphore(mutex1); // unlock
}
cout << "Database After Read = " << database << endl;
}while (true);
//-----------------------WRITER---------------------//
do{
cout << "Database Before Write = " << database << endl;
obj.waitSemaphore(wrt);//lock
//writing is preformed
database = database + 10;
obj.signalSemaphore(mutex1);//unlock
cout << "Database After Write = " << database << endl;
}while(true);
pthread_join( mutex1, NULL);
pthread_join( wrt, NULL);
obj.deleteSemaphore(* mutex1);
obj.deleteSemaphore(* wrt);
return 0;
}
void reader_writer () {}
Here is an error I get:
what type do they need to be? pthread_mutex_t_create? or pthread_t_create?
what is the proper type?
Functions inside a class are called methods. You need to instantiate an object of that class to be able to use it's methods:
myCountingSemaphoreUsingBinarySemaphore obj; // obj is an instance of the class
obj.waitSemaphore(&mutex1);
obj.signalSemaphore(&mutex1);
EDIT:
By the way, pthread_create and pthread_join take a pthread_t* and not a mutex!
int pthread_create(pthread_t* thread,
pthread_attr_t* attr,
void* (*start_routine)(void*),
void* arg);
You can either declare those methods as static or use an object to make the calls:
myCountingSemaphoreUsingBinarySemaphore s;
s.waitSemaphore(wrt);
You are calling class methods as just waitSemaphore without creating the object of myCountingSemaphoreUsingBinarySemaphore.
You should create the object first.
myCountingSemaphoreUsingBinarySemaphore obj;
obj.waitSemaphore(mutex1);
The two threads you create (via reader_writer()) do nothing. main() just goes into the first do loop with no way of getting out.
Also, you seem to have confused mutex, semaphores, and condition variables. The function names makes it look like you're trying to implement condition variables in your class. But you're building it as just wrappers to mutex locks.
And finally, you are calling pthread_mutex_lock() et al. on a pthread_t when those functions are supposed to be called on a pthread_mutex_t.
There probably are other errors, but these are the ones that really jump out. Basically, you need to review multi-threaded programming, both in terms of how threads are created, and how they are synchronized.
You need to create an instance of the class (an object) in order to call his member functions.
In this particular code the member functions has no reason to be instance and could be static:
class foo{
public:
static void bar(int val)
{
//do something
}
};
int main()
{
foo::bar(10);
}
karlphillip was right, you need to pass by pointer instead of reference
BTW, following line are mistake also, the pthread_create accept and pthread_t instead of pthread_mutex_t
pthread_create( &mutex1, NULL, reader_writer, void);
pthread_create( &wrt, NULL, reader_writer, void);
I am having problems calling my functions from my main program.
These functions HAVE to be in my class.
How do I access them from my int main()?
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <semaphore.h>
#include <synch.h>
using namespace std;
class myCountingSemaphoreUsingBinarySemaphore {
public:
void waitSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_lock(*thread);// Makes value 1 (Not Available)
}
void signalSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_unlock(*thread); // Makes value 0 (Available)
}
void deleteSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_destroy(*thread);// Deletes
}
};
int readerCount;
int database = (rand() / 100); // Number less than 1000
void reader_writer(void);
int main(int argc, char *argv[])
{
myCountingSemaphoreUsingBinarySemaphore obj;
pthread_mutex_t mutex1;
pthread_mutex_t wrt;
pthread_create( &mutex1, NULL, reader_writer, void);
pthread_create( &wrt, NULL, reader_writer, void);
//----------------------READER------------------------//
do{
cout << "Database Before Read = " << database << endl;
obj.waitSemaphore(mutex1);//lock
readerCount++;
if (readerCount == 1)
{
obj.waitSemaphore(wrt);//lock
obj.signalSemaphore(mutex1);//unlock
//reading is preformed
obj.waitSemaphore(mutex1); // lock
readerCount--;
}
if(readerCount == 0)
{
obj.signalSemaphore(wrt);//unlock
obj.signalSemaphore(mutex1); // unlock
}
cout << "Database After Read = " << database << endl;
}while (true);
//-----------------------WRITER---------------------//
do{
cout << "Database Before Write = " << database << endl;
obj.waitSemaphore(wrt);//lock
//writing is preformed
database = database + 10;
obj.signalSemaphore(mutex1);//unlock
cout << "Database After Write = " << database << endl;
}while(true);
pthread_join( mutex1, NULL);
pthread_join( wrt, NULL);
obj.deleteSemaphore(* mutex1);
obj.deleteSemaphore(* wrt);
return 0;
}
void reader_writer () {}
Here is an error I get:
what type do they need to be? pthread_mutex_t_create? or pthread_t_create?
what is the proper type?
Functions inside a class are called methods. You need to instantiate an object of that class to be able to use it's methods:
myCountingSemaphoreUsingBinarySemaphore obj; // obj is an instance of the class
obj.waitSemaphore(&mutex1);
obj.signalSemaphore(&mutex1);
EDIT:
By the way, pthread_create and pthread_join take a pthread_t* and not a mutex!
int pthread_create(pthread_t* thread,
pthread_attr_t* attr,
void* (*start_routine)(void*),
void* arg);
You can either declare those methods as static or use an object to make the calls:
myCountingSemaphoreUsingBinarySemaphore s;
s.waitSemaphore(wrt);
You are calling class methods as just waitSemaphore without creating the object of myCountingSemaphoreUsingBinarySemaphore.
You should create the object first.
myCountingSemaphoreUsingBinarySemaphore obj;
obj.waitSemaphore(mutex1);
The two threads you create (via reader_writer()) do nothing. main() just goes into the first do loop with no way of getting out.
Also, you seem to have confused mutex, semaphores, and condition variables. The function names makes it look like you're trying to implement condition variables in your class. But you're building it as just wrappers to mutex locks.
And finally, you are calling pthread_mutex_lock() et al. on a pthread_t when those functions are supposed to be called on a pthread_mutex_t.
There probably are other errors, but these are the ones that really jump out. Basically, you need to review multi-threaded programming, both in terms of how threads are created, and how they are synchronized.
You need to create an instance of the class (an object) in order to call his member functions.
In this particular code the member functions has no reason to be instance and could be static:
class foo{
public:
static void bar(int val)
{
//do something
}
};
int main()
{
foo::bar(10);
}
karlphillip was right, you need to pass by pointer instead of reference
BTW, following line are mistake also, the pthread_create accept and pthread_t instead of pthread_mutex_t
pthread_create( &mutex1, NULL, reader_writer, void);
pthread_create( &wrt, NULL, reader_writer, void);