从线程执行成员方法时出现分段错误

时间:2018-05-18 11:21:42

标签: c++ multithreading mutex unique-lock

我正在尝试学习std :: threads,std :: mutex和std :: unique_lock。 想法是创建5个线程。

请求将被写入队列,5个线程将​​从队列中获取请求并进行处理。

如果队列为空,则线程将等待,这将继续,直到用户键入" done"。

代码执行干净的编译。

当我执行它时,在创建线程时会导致分段错误。

无法从调试器中弄清楚我做错了什么。请帮忙。

#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);
}

0 个答案:

没有答案