我正在尝试学习 std::threads、std::mutex 和 std::unique_lock。这个想法是创建5个线程。
请求将被写入队列,5 个线程将从队列中提取请求并处理它。
如果队列为空,线程将等待,这将一直持续到用户键入“完成”。
该代码进行了干净的编译。
当我执行它时,它会在创建线程时导致分段错误。
无法从调试器中弄清楚我做错了什么。请帮忙。
#0 0x0000003710e0e45c in _dl_fixup () from /lib64/ld-linux-x86-64.so.2
#1 0x0000003710e14c55 in _dl_runtime_resolve () from /lib64/ld-linux-x86-
64.so.2
#2 0x0000003713ab65a7 in
std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>) ()
from /usr/lib64/libstdc++.so.6
#3 0x000000000040247a in std::thread::thread<void (ThreadPool::*)(),
ThreadPool* const> (this=0x7fffffffe3a0, __f=@0x7fffffffe3b0,
__args#0=@0x7fffffffe3a8)
at /usr/lib/gcc/x86_64-redhat-
linux/4.4.7/../../../../include/c++/4.4.7/thread:133
#4 0x0000000000401f1c in ThreadPool::createthreads (this=0x7fffffffe3f0,
count=5) at ThreadPool.cpp:73
#5 0x00000000004016e4 in main () at ThreadPool.cpp:99
这是完整的代码
#include <queue>
#include <string>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <condition_variable>
using namespace std;
void handler(string req, int s)
{
cout << "Process request " << req << " by thread " <<
this_thread::get_id()<<endl;;
}
class ThreadPool
{
vector<thread> threadlist;
queue<pair<string, int> > requestQueue;
mutex qLock;
condition_variable queued;
volatile bool breakout;
void (*callback)(string,int);
public:
ThreadPool()
{
breakout=false;
}
void setcallback(void (*fp)(string, int))
{
callback=fp;
}
void worker()
{
while (!breakout)
{
pair<string, int> request;
{
unique_lock<mutex> lock(qLock);
while((!breakout) && (requestQueue.empty()))
{
queued.wait(lock);
}
if (!requestQueue.empty())
{
request = requestQueue.front();
requestQueue.pop();
}
}
if (!request.first.empty())
{
callback(request.first,request.second);
}
}
}
void createthreads(int count)
{
for (int i=0;i<count;i++)
{
threadlist.push_back(thread(&ThreadPool::worker,this));
}
}
};
int main()
{
ThreadPool tp;
tp.setcallback(handler);
tp.createthreads(5);
return(0);
}