且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c ++ 11中线程库使用的问题

更新时间:2022-05-01 23:00:11

这是因为消费者和生产者线程比主线程更长(你的程序在创建线程后立即终止)。

试试,例如:

That's because the consumer and producer threads outlive the main thread (your program terminates immediately after thread creation).
Try, for instance:
#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();
}