A class of portable threads implemented in C ++

When writing C programs that need to split a file's scope variable between the application and the interrupt routine / thread / callback procedure, it is well known that the variable must be declared mutable, otherwise the compiler may make incorrect optimizations. This is an example of what I mean:

int flag;

void some_interrupt (void)
{
  flag = 1;
}



int main()
{
  flag = 0;
  ...

  /* <-- interrupt occurs here */

  x = flag; /* BUG: the compiler doesn't realize that "flag" was changed 
                    and sets x to 0 even though flag==1 */

}

To prevent the above error, the flag should be declared as mutable.

My question is: how is this applicable to C ++ when creating a class containing a stream?

I have a class that looks something like this:

class My_thread
{
  private:
    int flag;

    static void thread_func (void* some_arg) // thread callback function
    {
      My_thread* this_ptr= (My_thread*)some_arg;

    }
};

"some_arg" will contain a pointer to an instance of the class, so each "My_thread" object has its own thread. Through this pointer, it will access member variables.

, "this_ptr" ? "" ? , -, "" volatile?

, , , .

EDIT: !

..

, , , , , . , C, , ++.

+3
4

, . . volatile . int flag .

. volatile , redudant - . .
+2

, posix . , , API. boost thread. , - , Java.

class Runnable {
    public:
        virtual void run() = 0;
};

class Thread : public Runnable {
    public:
        Thread();
        Thread(Runnable *r);

        void start();
        void join();        

        pthread_t getPthread() const;

    private:

        static void *start_routine(void *object);

        Runnable *runner;
        pthread_t thread;
};

- start_routine:

void* Thread::start_routine(void *object) {
    Runnable *o = (Runnable *)object;

    o->run();

    pthread_exit(NULL);
    return NULL;
}

, Runnable Thread, , .

, , , , , ...

0

Windows, Linux. :

typeReadFileCallback varCallback;

.

0

, :

volatile -

:

volatile , . , , , - , . , : . : , , , . , ; , .

0
source

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


All Articles