本文介绍了c ++ 11中线程库使用的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用线程库,当线程是类的成员函数时

假设我在一个类中有2个线程



我尝试过:



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:
};



其中producerth和consumerth()有true循环,

并运行工具as以下:


where producerth and consumerth() have while true loop,
and run implements as following:

void run()
{
      producer()
      consumer()
}





我以不寻常的方式终止运行时间异常



帮我修复bug



I got the run time termination in an unusual way exception

help me to fix the bug

推荐答案

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


这篇关于c ++ 11中线程库使用的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:44
查看更多