How to create a stream inside a class function?

I am very new to C ++.

I have a class and I want to create a stream inside a class function. And this thread (function) will call and get access to the class function and variable. At first I tried to use Pthread, but worked only outside the class, if I want to access the function / variable of the class, I got an error outside the scope. I am looking at Boost / thread, but this is undesirable because I do not want to add any other library to my files (for another reason).

I did some research and did not find any useful answers. Please give some examples to help me. Thank you very much!

Trying to use pthread (but I don’t know how to deal with the situation I mentioned 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; } 
+4
source share
2 answers

You can pass a static member function to pthread and an object instance as an 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 an example of pthread. You can probably adapt it to use std :: thread without too much difficulty.

+12
source
 #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(); } 
+7
source

Source: https://habr.com/ru/post/1443765/


All Articles