c++ - 从调用这些线程的“母亲”类对象中的线程访问方法
问题描述
我想调用从这个线程创建线程的类中的一个函数。
目前我有两个类,一个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 的引用?我的第二个问题是:我添加的同步是否足够?
更新:我不希望我的助手等待传入数据。应该可以保持循环并定期检查现在数据是否已到达。如果发现新数据,则应处理此数据,否则我的助手应继续做其他事情。
解决方案
推荐阅读
- java - 活动重启后Recyclerview不更新
- jsoup - 在 XML Payload 中转义 HTML 字符/标签
- c - 我什么时候必须释放分配的内存?
- javascript - 自动完成在keyup jquery中的奇怪行为
- mysql - 我应该怎么做才能根据条件加入 2 个表?
- sql - SQL 存储过程 - 代码长度 > 8,000 时运行错误
- api - 在响应模型中传递数据库约束是 REST 好/坏的做法吗
- javascript - Treemap 中不同的工具提示和值 || 海图
- listview - (FLUTTER) ontap ListView(return listTile()) with Streambuilder 导致继承数据为空?
- java - Cassandra - 将一个巨大的字段设置为 null 不归还磁盘空间