首页 > 解决方案 > 从调用这些线程的“母亲”类对象中的线程访问方法

问题描述

我想调用从这个线程创建线程的类中的一个函数。

目前我有两个类,一个Helper-Class和我的Async-Worker-Class

首先,我的Helper-Class在我的main()中实例化。该线程是在Helper-Class中创建的。应该可以实例化多个Helper-Class。因此,实例和线程的数量是相同的。

int main(){
    //This is where my helper is constructed
    Helper myHelper_1();
    Helper myHelper_2();

}

现在我的助手类看起来像这样。Helper-Class的构造函数创建了一个新线程——我将其命名为t1

class Helper {
    std::stack <std::string> names_for_adding;
    std::mutex helper_lock;

    void processName(std::string name);


    // The constructor of my "mother"-class constructs the thread
    Helper() {
        // I've created an instance of AsyncThread
        AsyncThread my_async_worker();

        //Call the thread
        std::thread t1(&AsyncThread::scan, &my_async_worker);
        t1.detach();

        while(true) {
            std::cout << "Doing some stuff.." << std::endl;

            //Now oi check if my
            helper_lock.lock();
            std::string my_name = names_for_adding.top();
            names_for_adding.pop();
            // E. g. process the name
            processName(my_name);
            helper_lock.unlock();
        }
    }

    void addToQueue(std::string name) {
        helper_lock.lock();
        names_for_adding.push(name);
        helper_lock.unlock();
    }
};

第二类,AsyncThread的唯一目的是在运行时“扫描”。例如,一项任务可能是接收不定期的不同日期(例如名称)(来自管道或套接字)。如果名称与给定的过滤器匹配(例如“foo”),我想将此通知我的Helper-Instance并将找到的名称添加到队列中以进行进一步处理。

class AsyncThread {

public:
    void scan() {
        std::string name;
        //Doing the scan procedure
        //...
        while (true) {
            // ...Receiving names ...
            // A name has been found which matches the given filter
            if (name == "foo") {
                std::cout << "Name found, adding to helper" << std::endl;
                //like: myHelper_1.addToQueue(name)
                //now i want to call the function 'addToQueue' from my
                //my class helper (which is also an object)
            }
        }
    }
};

现在我的问题是如何以线程安全的方式实现这一点?是否可以(并且允许或良好做法)将我的线程传递给调用 Helper-Instance 的引用?我的第二个问题是:我添加的同步是否足够?

更新:我不希望我的助手等待传入数据。应该可以保持循环并定期检查现在数据是否已到达。如果发现新数据,则应处理此数据,否则我的助手应继续做其他事情。

标签: c++multithreadingthread-safety

解决方案


推荐阅读