第四十三行std::mutex mtx一旦定义为静态成员就会出现无法解析的外部符号错误,我明白没有把这个互斥锁定义为静态成员的必要,可是也不明白为什么这样做会导致错误
#if 1
#include<iostream>
#include<thread>
#include<mutex>
#include<queue>
#define TASKS_NUM 10
class TaskQueue
{
public:
TaskQueue(const TaskQueue& taskQueue) = delete;
TaskQueue& operator=(const TaskQueue& taskQueue) = delete;
static TaskQueue* getInstance() {
return taskQueue;
}
bool isEmpty() {
std::lock_guard<std::mutex> lck(mtx);
return tasks.empty();
}
bool delTask() {
std::lock_guard<std::mutex> lck(mtx);
if (tasks.empty())return false;
tasks.pop();
return true;
}
int getTask() {
std::lock_guard<std::mutex> lck(mtx);
if (tasks.empty())return 0;
int t = tasks.front();
tasks.pop();
return t;
}
void pushTask(int i) {
std::lock_guard<std::mutex> lck(mtx);
tasks.push(i);
}
private:
TaskQueue() = default;
std::mutex mtx;
std::queue<int> tasks;
static TaskQueue* taskQueue;
};
TaskQueue* TaskQueue::taskQueue = new TaskQueue;
int main() {
TaskQueue* instance = TaskQueue::getInstance();
std::thread tBoss([=]() {
for (int i = 1; i < TASKS_NUM; i++) {
instance->pushTask(i);
std::cout << std::this_thread::get_id() << ":老板布置任务" << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
});
std::thread tEmployee([=]() {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
while(!instance->isEmpty()) {
int t = instance->getTask();
std::cout << std::this_thread::get_id() << ":员工完成任务" << t << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(800));
}
});
tBoss.join();
tEmployee.join();
}
#endif