在构造函数中创建线程 [英] Thread creation inside constructor

查看:586
本文介绍了在构造函数中创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在使用C ++ 11并制作了一个类

So, I am using C++11 and I made a class

Class C
{
  private:
    queue<std::int> s;
    pthread_t x;
  public:
    C() {phthread_create(&x, NULL, d_q, NULL);
    void log(int p); // pushes into q.
    void* d_q(void* q); // this is a function which will pop s. assume s is thread safe.
}

问题是行pthread_create(&x, NULL, d_q, NULL).它给了我Error: Reference to non-static member must be called.

我通过制作pthread_t x static摆脱了这个问题.但由于两个原因,我不想这样做:

I get rid of this problem by making pthread_t x static. But I dont want to do this because of 2 reasons:

  1. 使用静态函数创建线程意味着该函数只有1个副本.
  2. 该线程是在构造函数中创建的.我不知道如果创建多个类C的对象会发生什么情况.

有人可以给我一个解决方法吗?

Can someone please give me a workaround?

已解决:感谢您的帮助! 另外,对于以后的用户来说,相对于pthread,更推荐使用std :: thread更好!

Solved: Thanks for the help! Also, a very good advice is to prefer std::thread over pthread for future users!

推荐答案

对于您的问题,您指向(非静态)成员函数的指针相同成员函数.非静态成员函数需要调用对象的实例.

As for your problem, you a pointer to a (non-static) member function is not the same as a pointer to a member function. Non-static member functions needs an instance of an object to be called on.

有两种方法可以解决此问题:如果您坚持使用POSIX线程函数,则可以制作一个static包装器函数,将该实例作为参数传递给该线程,然后在静态包装器函数中调用使用传递的对象的实际功能.

There are a couple of ways to solve this: If you insist on using POSIX thread functions then you could make a static wrapper function, pass the instance as an argument to the thread, and in the static wrapper function call the actual function using the object passed.

另一种解决方案是使用 std::thread 更容易:

Another solution is to use std::thread, which will make it much easier:

class C
{
    std::thread thread_;
    ...
public:
    C() : thread_(&C::d_q, this) {}
    ...
    void d_q() { ... }
};

这篇关于在构造函数中创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆