-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
线程池 threadpool<T>::run() 函数中,为什么要判断 request 非NULL? #276
Comments
我又发现 m_queuestat.wait();
m_queuelocker.lock();
if (m_workqueue.empty())
{
m_queuelocker.unlock();
continue;
} 我也想不到任何触发这个if的情况。我查了下, 我只能理解这里是在做防御性编程了。。 |
同问 |
第一个应该仅仅是防御性编程, 因为调用 process 前 必先 经过 read_once, 所以确实不会有null的风险。 #include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
queue<int> gifts;
mutex mtx;
condition_variable cv;
void produce() {
for (int i = 1; i <= 5; i++) {
mtx.lock();
gifts.push(i);
mtx.unlock();
cv.notify_one();
}
//约定0 为 退出
mtx.lock();
gifts.push(0);
mtx.unlock();
cv.notify_one();
}
void consume() {
while (true) {
unique_lock<mutex> lk(mtx);
//一直等到 !gifts.empty() 为真
cv.wait(lk, [] {return !gifts.empty(); });
auto gift = gifts.front();
gifts.pop();
lk.unlock();
cout << "礼物:" << gift << endl;
if (gift == 0)
break;
}
}
int main() {
thread(produce).detach();
consume();
} |
我想不到任何一种情况会导致
request
为NULL
,也就是下面的代码我觉得是没必要的:threadpool<T>::run()
用的request
最先是WebServer::dealwithwrite()
和WebServer::dealwithread()
中append
操作进来的。append
是类似m_pool->append(users + sockfd, 1);
这样直接操作的 users 数组。但是我们看到WebServer::WebServer()
构造函数内是直接users = new http_conn[MAX_FD];
的,因此users + sockfd
在任何时候都不可能为NULL
。即使WebServer::~WebServer()
析构函数内做了delete[] users;
,但 delete 关键字本身也不会改变指针的值,所以根本想不到为什么代码中要判断request
为NULL
....看看有无大佬分析一下这里。
The text was updated successfully, but these errors were encountered: