I am trying to create a thread in the main function for the function named thefunction() in the ThreadMe class. The tricky part is that I need to start a thread in another class TYIA -Roland
#include <iostream>
#include <process.h>
#include <windows.h>
int main() {
char cincatcher[24];
std::cout << "I want to run a thread using a function on another class\n";
// Here is a good place to start the thread
while( true ) {
std::cin >> cincatcher
}
}
class ThreadMe {
void thefunction();
};
void ThreadMe::thefunction() {
while( true ) {
std::cout << "working!\n"
Sleep(800);
}
}
You cannot start thread directly with a class method. You must wrap the class method into a normal function, then start thread with the function. Like the following:
void threadBody(void *p) {
ThreadME tm;
tm.thefunction();
}
Related
I have a class foo and i put inside a member function a thread object. And i tried to initialize it like this std::thread mythread(&foo::myprint, this); inside another function. My problem is that I get the same thread::get_id with a different function foo::mycount that i need to count something. Both myprint and mycount uses this_thread::sleep_for but they don't sleep separately (something that i want to happen). I follow you up with some code example
class foo
{
void func()
{
std::thread mythread(&foo::myprint, this);
mythread.join();
}
void myprint()
{
sleep_for(1s);
cout << count << endl;
}
void mycount()
{
sleep_for(1ms);
count++;
cout << count << endl;
}
};
void main()
{
foo obj;
while(1)
{
obj.func();
obj.mycount();
}
}
I also tried putting mycount in another function with a thread object, and I don't if std::call_once affected anything, cause i used it inside the mycount function. I expected a different get_id for different functions.
Here is an example with a lambda function to start an asynchronous process.
And using std::future for synchronizing the destructor of your class with the background thread (which is counting numbers in this example).
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
// dont do "using namespace std"
using namespace std::chrono_literals;
class foo
{
public:
foo() = default;
~foo()
{
// destructor of m_future will synchronize destruction with execution of the thread (waits for it to finish)
}
void func()
{
m_future = std::async(std::launch::async, [=] { myprint(); });
}
void myprint()
{
for (std::size_t n = 0; n < 5; ++n)
{
std::this_thread::sleep_for(1s);
std::cout << n << " ";
}
std::cout << "\n";
}
private:
std::future<void> m_future;
};
int main()
{
foo obj;
obj.func(); // start thread
return 0;
}
I am currently practicing the use of multiple threads in C++. The program is simplified as follow. In this case, I have a global variable Obj, and within each task, a get function is processed by thread and thread detach will be called after.
In practice, get may take a great amount of time to run. If there are many tasks, get will be called repetitively (since each task has its own get function). I wonder if I can design a program where when one task has already obtained the data using get function and the data has been wrote to obj.text, then the rest of tasks can directly access or wait for the data from obj.text.
Can I use std::shared_ptr, std::future, std::async in c++ to implement this? If so, how to design the program? Any advice is greatly appreciated.
#include <chrono>
#include <future>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
using namespace std;
class Info {
public:
Info() { Ids = 10; };
int Ids;
std::string text;
};
Info Objs;
class Module {
public:
Module() {}
virtual void check(int &id){};
virtual void get(){};
};
class task1 : public Module {
public:
task1() { std::cout << "task1" << std::endl; }
void check(int &id) override {
thread s(&task1::get, this);
s.detach();
};
// The function will first do some other work (here, I use sleep to represent
// that) then set the value of Objs.text
void get() override {
// The task may take 2 seconds , So use text instead
std::this_thread::sleep_for(std::chrono::seconds(5));
Objs.text = "AAAA";
std::cout << Objs.text << std::endl;
};
};
class task2 : public Module {
public:
task2() { std::cout << "task2" << std::endl; }
void check(int &id) override {
thread s(&task2::get, this);
s.detach();
};
// The function will first do some other work (here, I use sleep to represent
// that) then set the value of Objs.text
void get() {
std::this_thread::sleep_for(std::chrono::seconds(5));
Objs.text = "AAAA";
std::cout << Objs.text << std::endl;
};
};
int main() {
std::vector<std::unique_ptr<Module>> modules;
modules.push_back(std::make_unique<task1>());
modules.push_back(std::make_unique<task2>());
for (auto &m : modules) {
m->check(Objs.Ids);
}
std::this_thread::sleep_for(std::chrono::seconds(12));
return 0;
}
It is a plain producer-consumer problem.
You have multiple “get()” producers. And did not implemented consumers yet.
First, you should have multiple “Info” for multithread. If there is only one Info, multithread programming is useless. I recommend “concurrent_queue”.
Second, “detach()” is not a good idea. You can’t manage child threads. You’d better use “join()”
My code sample follows. I used Visual Studio 2022
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include <concurrent_queue.h>
using namespace std;
class Info {
public:
Info() { Ids = 10; };
int Ids;
std::string text;
};
concurrency::concurrent_queue<Info> Objs;
void producer()
{
while (true) {
Info obj;
std::this_thread::sleep_for(std::chrono::seconds(5));
obj.text = "AAAA\n";
Objs.push(obj);
}
}
void consumer()
{
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
Info obj;
bool got_it = Objs.try_pop(obj);
if (got_it) {
std::cout << obj.text;
}
}
}
int main() {
const int NUM_CORES = 6;
std::vector<std::thread> threads;
for (int i = 0; i < NUM_CORES / 2; ++i)
threads.emplace_back(producer);
for (int i = 0; i < NUM_CORES / 2; ++i)
threads.emplace_back(consumer);
for (auto& th : threads) th.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);