函数对象和多线程池提供相同的线程ID



对于下面的程序,线程池总是选择相同的线程ID 0x7000095f9000!为什么会这样?是否每个推送条件notify_one((都应该同时唤醒所有线程?选择相同线程ID的原因是什么?

计算机支持3个线程。任何其他关于使用函数对象的信息都会很有帮助!!

O/p

Checking if not empty
Not Empty
0x700009576000 0
Checking if not empty
Checking if not empty
Checking if not empty
Not Empty
0x7000095f9000 1
Checking if not empty
Not Empty
0x7000095f9000 2
Checking if not empty
Not Empty
0x7000095f9000 3
Checking if not empty
Not Empty
0x7000095f9000 4
Checking if not empty
Not Empty
0x7000095f9000 5
Checking if not empty

代码

#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <condition_variable>
#include <chrono>
using namespace std;
class TestClass{
public:
void producer(int i) {
unique_lock<mutex> lockGuard(mtx);
Q.push(i);
cond.notify_all();
}

void consumer() {
{
unique_lock<mutex> lockGuard(mtx);
cout << "Checking if not empty" << endl;
cond.wait(lockGuard, [this]() {
return !Q.empty();
});
cout << "Not Empty" << endl;
cout << this_thread::get_id()<<" "<<Q.front()<<endl;
Q.pop();
}
};
void consumerMain() {
while(1) {
consumer();
std::this_thread::sleep_for(chrono::seconds(1));
}
}
private:
mutex mtx;
condition_variable cond;
queue<int> Q;
};

int main()
{
std::vector<std::thread> vecOfThreads;
std::function<void(TestClass&)> func = [&](TestClass &obj) {
while(1) {
obj.consumer();
}
};
unsigned MAX_THREADS = std::thread::hardware_concurrency()-1;
TestClass obj;
for(int i=0; i<MAX_THREADS; i++) {
std::thread th1(func, std::ref(obj));
vecOfThreads.emplace_back(std::move(th1));
}
for(int i=0; i<4*MAX_THREADS/2; i++) {
obj.producer(i);
}
for (std::thread & th : vecOfThreads)
{
if (th.joinable())
th.join();
}
return 0;
}

任何其他关于使用函数对象的信息都会很有帮助!!提前感谢!!还有其他指针吗?

在您的情况下,消费者线程中发生的mutex的极短解锁很可能会让运行的线程一次又一次地获得锁。

如果您通过调用consumerMain(它会休眠一点(而不是consumer来模拟从队列中提取工作负载后所做的一些工作,那么您可能会看到不同的线程在提取工作负载。

while(1) {
obj.consumerMain();
}

最新更新