Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I want to use thread library, when the thread is member function of class
assume I have 2 thread in a class

What I have tried:

class produceconsume
{
    public:
        produceconsume();
        virtual ~produceconsume();
        thread producer()
        {
            return std::thread(&producerth, this);
        }
        thread consumer()
        {
            return std::thread(&consumerth, this);
        }
        void producerth();
        void consumerth();
        void run();
    private:
};

where producerth and consumerth() have while true loop,
and run implements as following:
void run()
{
      producer() 
      consumer()
}


I got the run time termination in an unusual way exception

help me to fix the bug
Posted
Updated 23-Oct-18 21:00pm

1 solution

That's because the consumer and producer threads outlive the main thread (your program terminates immediately after thread creation).
Try, for instance:
C++
#include <iostream>
#include <thread>

class produceconsume
{
    public:
        produceconsume(){}
        virtual ~produceconsume(){}
        std::thread producer()
        {
            return std::thread(&produceconsume::producerth, this);
        }
        std::thread consumer()
        {
            return std::thread(&produceconsume::consumerth, this);
        }
        void producerth();
        void consumerth();
        void run();
    private:
};

void produceconsume::producerth()
{
  while (true) {}
}
void produceconsume::consumerth()
{
  while (true) {}
}
void produceconsume::run()
{
  auto tp = producer();
  auto tc = consumer();
  tc.join();
  tp.join();
}
 
Share this answer
 
Comments
saide_a 24-Oct-18 3:08am    
Many thanks , it works
CPallini 24-Oct-18 3:48am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900