|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
×
我在尝试做一个生产者+消费者多线程模型的时候,在进行调试时,出现报错:
0xC0000005: 读取位置 0x0000000000000070 时发生访问冲突。
以下是我的源代码(生产者部分被略去):
- export module core.thread;
- import std;
- import core.constants;
- using function = std::function<void()>;
- using lock = std::lock_guard<std::mutex>;
- export namespace thread
- {
- class Group
- {
- protected:
- std::queue<function> queue;
- public:
- std::condition_variable variable;
- std::mutex mutex;
- Group() = default;
- Group(const Group&) = delete;
- Group(Group&&) = delete;
- std::optional<function> get_task() noexcept
- {
- lock lock(this->mutex);
- if (this->queue.empty())
- {
- return std::nullopt;
- };
- function task = this->queue.front();
- this->queue.pop();
- return task;
- };
- void add_task(function task) noexcept
- {
- lock lock(this->mutex);
- this->queue.push(task);
- this->variable.notify_one();
- };
- };
- class BasicThread
- {
- protected:
- std::thread thread;
- choice::status status;
- std::string name;
- public:
- BasicThread() = delete;
- BasicThread(const BasicThread&) = delete;
- BasicThread(BasicThread&&) = default;
- BasicThread(const std::string& name) :
- name(name)
- {
- this->thread = std::thread(&BasicThread::run, this);
- };
- virtual void run() {};
- inline void join() noexcept
- {
- if (this->thread.joinable())
- {
- this->thread.join();
- };
- };
- };
- class Worker : public BasicThread
- {
- protected:
- std::shared_ptr<Group> group;
- public:
- Worker() = delete;
- Worker(const Worker&) = delete;
- Worker(Worker&&) = default;
- Worker(const std::string& name, const std::shared_ptr<Group>& group) :
- BasicThread(name),
- group(group) {};
- void run()
- {
- std::optional<function> current_task;
- while (this->status != choice::status::terminating)
- {
- std::unique_lock<std::mutex> lock{ this->group->mutex };
- this->group->variable.wait(lock, [¤t_task, this]() {return current_task = this->group->get_task(); }); // Only runs if a new task is available
- lock.unlock();
- current_task.value()();
- };
- };
- inline void attach(const std::shared_ptr<Group>& group) noexcept
- {
- this->group = group;
- };
- };
- };
复制代码
这是我的调试部分:
- import core.thread;
- import std;
- int main()
- {
- std::shared_ptr<thread::Group> group;
- thread::Worker worker{ "test", group };
- return 0;
- };
复制代码 |
|