Segmentation fault when executing member method from thread

824 views Asked by At

I am trying to learn the std::threads, std::mutex and std::unique_lock. The idea is to create 5 threads.

Requests will be written to a queue and the 5 threads will pick up request from the queue and process it.

If the queue is empty the threads will wait and this will continue until the user keys in "done".

The code does a clean compile.

When I execute it causes a segmentation fault when the thread is created.

Not able to figure out what I am doing wrong from the debugger. Please help.

#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

Here is the full code

#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

There are 0 answers