【问题标题】:How to spawn multiple threads that call same function using std::thread C++ [closed]如何使用 std::thread C++ 生成多个调用相同函数的线程 [关闭]
【发布时间】:2023-04-03 12:13:01
【问题描述】:

基本上我想做的是编写一个生成多个线程的 for 循环。线程必须多次调用某个函数。所以换句话说,我需要每个线程在不同的对象上调用相同的函数。如何使用 std::thread c++ 库做到这一点?

【问题讨论】:

  • 如果你能给出一些你已经尝试过的指示会很有帮助。

标签: c++ multithreading c++11 stdthread


【解决方案1】:

您可以简单地在循环中创建线程,每次传递不同的参数。在此示例中,它们存储在 vector 中,以便以后可以加入。

struct Foo {};

void bar(const Foo& f) { .... };

int main()
{
  std::vector<std::thread> threads;
  for (int i = 0; i < 10; ++i)
    threads.push_back(std::thread(bar, Foo()));

  // do some other stuff

  // loop again to join the threads
  for (auto& t : threads)
    t.join();
}

【讨论】:

    【解决方案2】:

    创建一个循环,每次迭代构造一个单独的线程对象,所有线程对象都具有相同的函数但不同的对象作为参数。

    【讨论】:

    • 为什么我不能使用相同的参数?
    • @tomtom1-4 如果您在循环内定义一个对象,您将不同的对象(“不同的参数”)传递给线程。即使在循环中对象的名称相同,对象本身也会在循环的每次迭代中被创建、复制(到线程)和销毁。如果您查看juanchopanza answer 中的示例,您会看到他每次迭代都执行Foo() 来创建一个对象,因此当他传递“相同的参数”时,它实际上是不同的对象。
    【解决方案3】:

    如果你想使用一些 C++11 的东西并利用 std::function + std::bind 的强大功能,你可以尝试这样的事情:

    #include <thread>
    #include <functional>
    #include <iostream>
    #include <vector>
    #include <memory>
    
    typedef std::function<void()> RunningFunction;
    
    class MyRunner 
    {
    private:
        MyRunner(const MyRunner&);
        MyRunner& operator=(const MyRunner&);
        std::vector<std::thread> _threads;
    
    public:
    
        MyRunner(uint32_t count, RunningFunction fn) : _threads()
        {
            _threads.reserve(count);
            for (uint32_t i = 0; i < count; ++i)
                _threads.emplace_back(fn);
        }
    
        void Join()
        {
            for (std::thread& t : _threads)
                if (t.joinable())
                    t.join();
        }
    };
    
    typedef std::shared_ptr<MyRunner> MyRunnerPtr;
    
    class Foo
    {
    public:
        void Bar(uint32_t arg)
        {
            std::cout << std::this_thread::get_id() << " arg = " << arg << std::endl;
        }
    };
    
    
    int calcArg()
    {
        return rand() % UINT32_MAX;
    }
    
    int main(int argc, char** argv)
    {
        std::vector<Foo> objs;
    
        for (uint32_t i = 0; i < 32; ++i)
            objs.emplace_back(Foo());
    
        std::vector<MyRunnerPtr> runners;
    
        for (Foo& obj : objs)
        {
            const uint32_t someArg = calcArg();
            runners.emplace_back(std::make_shared<MyRunner>(1, std::bind(&Foo::Bar, &obj, someArg)));
        }
    
        for (MyRunnerPtr& runner : runners)
            runner->Join();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多