我想实现一个可以从主线程接受函数指针并串行执行它们的线程。我的想法是使用一个结构来保存函数指针及其对象,并不断将其推送到队列中。这可以封装在一个类中。然后任务线程可以从队列中弹出并处理它。我还需要同步它(所以它不会阻塞主线程?),所以我在考虑使用信号量。虽然我对程序的结构有一个不错的了解,但我在编写代码时遇到了麻烦,尤其是 C++11 中的线程和信号量同步。如果有人可以提出一个大纲,我可以据此着手实现,那就太好了。
编辑:重复的问题回答了关于创建线程池的问题。看起来正在创建多个线程来完成一些工作。我只需要一个线程可以对函数指针进行排队并按接收到的顺序处理它们。
最佳答案
检查这个代码片段,虽然我没有使用类来实现。看看它是否有帮助。这里可以避免使用条件变量,但我希望读取器线程仅在有来自写入器的信号时才轮询,这样读取器中的 CPU 周期就不会被浪费。
#include <iostream>
#include <functional>
#include <mutex>
#include <thread>
#include <queue>
#include <chrono>
#include <condition_variable>
using namespace std;
typedef function<void(void)> task_t;
queue<task_t> tasks;
mutex mu;
condition_variable cv;
bool stop = false;
void writer()
{
while(!stop)
{
{
unique_lock<mutex> lock(mu);
task_t task = [](){ this_thread::sleep_for(chrono::milliseconds(100ms)); };
tasks.push(task);
cv.notify_one();
}
this_thread::sleep_for(chrono::milliseconds(500ms)); // writes every 500ms
}
}
void reader()
{
while(!stop)
{
unique_lock<mutex> lock(mu);
cv.wait(lock,[]() { return !stop;});
while( !tasks.empty() )
{
auto task = tasks.front();
tasks.pop();
lock.unlock();
task();
lock.lock();
}
}
}
int main()
{
thread writer_thread([]() { writer();} );
thread reader_thread([]() { reader();} );
this_thread::sleep_for(chrono::seconds(3s)); // main other task
stop = true;
writer_thread.join();
reader_thread.join();
}
关于c++ - 从主线程 c++11 执行函数调用的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48801235/