【问题标题】:Where to get simple Boost Thread Management example?从哪里获得简单的 Boost 线程管理示例?
【发布时间】:2023-04-04 22:56:01
【问题描述】:

所以我有一个简单的 cpp 文件。只有一个具有一个主函数和 3 个 int a-la 公共变量。喜欢:

   int a;
   int b;
   int c;
   void main()
   {
      startThredA();
      startThredB();
      while(1)
     {
        c = a + b;
        printf(c);
     }
   }

我想创建 2 个线程 A 和 B,其中一个应该为 A 生成随机值,为 b 生成另一个随机值。这种事情怎么办?

【问题讨论】:

  • Boost.Thread 文档的哪一部分您不明白?
  • @Sam - 我不明白它只是一个没有任何示例的函数和类列表的部分。这几乎不是一个清晰的模型,使进入的门槛高于应有的水平。
  • @Steve:那么您将@Sam 链接到的页面顶部的代码示例称为什么?例如“启动线程”标题下的那个。我将其称为“如何创建线程的示例”。 Boost 有很多带有糟糕或令人困惑的文档的库,但 Boost.Thread 尤其清晰、简洁且易于理解,imo。当然,它确实需要您阅读一些文档,但我认为这是公平的。

标签: c++ multithreading boost


【解决方案1】:

这是一个小而简单的例子。它已经过尝试,似乎工作正常。

#include <iostream>
#include <boost/thread.hpp>

namespace this_thread = boost::this_thread;

int a = 0;
int b = 0;
int c = 0;

class BaseThread
{
public:
    BaseThread()
        { }
    virtual ~BaseThread()
        { }

    void operator()()
    {
        try
        {
            for (;;)
            {
                // Check if the thread should be interrupted
                this_thread::interruption_point();

                DoStuff();
            }
        }
        catch (boost::thread_interrupted)
        {
            // Thread end
        }
    }

protected:
    virtual void DoStuff() = 0;
};

class ThreadA : public BaseThread
{
protected:
    virtual void DoStuff()
    {
        a += 1000;
        // Sleep a little while (0.5 second)
        this_thread::sleep(boost::posix_time::milliseconds(500));
    }
};

class ThreadB : public BaseThread
{
protected:
    virtual void DoStuff()
    {
        b++;
        // Sleep a little while (0.5 second)
        this_thread::sleep(boost::posix_time::milliseconds(100));
    }
};

int main()
{
    ThreadA thread_a_instance;
    ThreadB thread_b_instance;

    boost::thread threadA = boost::thread(thread_a_instance);
    boost::thread threadB = boost::thread(thread_b_instance);

    // Do this for 10 seconds (0.25 seconds * 40 = 10 seconds)
    for (int i = 0; i < 40; i++)
    {
        c = a + b;
        std::cout << c << std::endl;

        // Sleep a little while (0.25 second)
        this_thread::sleep(boost::posix_time::milliseconds(250));
    }

    threadB.interrupt();
    threadB.join();

    threadA.interrupt();
    threadA.join();
}

【讨论】:

    【解决方案2】:

    有一系列文章starting here 应该会给你一些初步的指导。作者主要负责将 boost.thread 引入 C++0x。

    文章列表:

    C++0x 中的多线程第 1 部分:启动线程

    C++0x 中的多线程第 2 部分:使用函数对象和参数启动线程

    C++0x 中的多线程第 3 部分:使用成员函数和引用参数启动线程

    C++0x 中的多线程第 4 部分:保护共享数据

    C++0x 中的多线程第 5 部分:使用 std::unique_lock 灵活锁定

    C++0x 中的多线程第 6 部分:延迟初始化和使用原子的双重检查锁定

    C++0x 中的多线程第 7 部分:锁定多个互斥体而不发生死锁

    C++0x 中的多线程第 8 部分:Futures、Promises 和异步函数调用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-23
      • 2018-01-03
      • 2023-03-19
      • 2010-10-06
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多