|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
万行代码计划
Day03,100行
进度200/10000
/*20210728
std::unique_lock<std::mutex> lock(mutex);// 配合使用std::condition_variable::wait
cv.wait(lock,[]{return quit||!globalList.empty();});//加入等待条件
pool.emplace_back(worker,i);//右值引用,直接构造
cout线程不安全的,printf线程安全的
线程池
线程死循环等待写法避免,占用CPU过高,如何避免?
隔断时间看一下?
线程进入和退出的条件如何处理?
线程等待条件如何设置?
*/
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
#include <iostream>
#include <chrono>
#include <list>
#include <string>
#include <ctime>
#include <cstring>
#include<condition_variable>
class Message{
public:
const std::string& data() const{ return m_data;}
Message(std::string d = std::string()):m_data(std::move(d)){}
private:
std::string m_data;
};
std::atomic<int> toatalSize{0};
std::mutex mutex;
std::condition_variable cv;
std::atomic<bool> ready{false};
bool quit{false};
std::list<Message> globalList;
void worker(int i){
while (!ready){
}
Message msg;
while (!quit)
{
{
std::unique_lock<std::mutex> lock(mutex);// 配合使用std::condition_variable::wait
cv.wait(lock,[]{return quit||!globalList.empty();});//加入等待条件
if (quit)
{
return;
}
auto iter = globalList.begin();
msg = std::move(*iter);
globalList.erase(iter);
}
toatalSize += strlen(msg.data().c_str());
}
}
int main()
{
const auto threadCount = 4;
for (size_t i = 0; i < 500000; i++)
{
/* code */
globalList.push_back("this is a test"+std::to_string(i));
}
std::vector<std::thread> pool;
for (size_t i = 0; i < threadCount; i++)
{
pool.emplace_back(worker,i);//右值引用,直接构造
}
auto beginc = clock();
ready = true;
for (size_t i = 0; i < 300000; i++)
{
/* code */
{
std::lock_guard<std::mutex> lock(mutex);
globalList.push_back(std::string("second"));
}
cv.notify_one();
}
while (true)
{
/* code */
std::lock_guard<std::mutex> lock(mutex);
if (globalList.empty())
{
/* code */
quit = true;
cv.notify_all();
break;
}
}
for (auto &v:pool)
{
/* code */
if (v.joinable())
{
/* code */
v.join();
}
}
auto endc = clock();
std::cout<<"total size is "<<toatalSize<<" using time " << endc-beginc<<std::endl;
} |
|