Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault while creating thread using #include<thread>

I am new to C++ multithreading. I wrote a simple program to print hello world using threads.

<<mythread.cpp>>

#include<iostream>
#include<thread>
using namespace std;
void hello()
{
std::cout<<"Hi this is a thread";
}


int main()
{

std::thread mythread(hello);
cout<<'1';
if (mythread.joinable())
        {
        cout<<'2';
         mythread.join();
        cout<<'3';
        }

return 0;
}

Copilation command : g++ -std=c++0x mythread.cpp

It compiled successfully but gave Segmentaion fault at run time.

I check the core file :

(gdb) bt
#0  0x0000003ac340df7c in _dl_fixup () from /lib64/ld-linux-x86-64.so.2
#1  0x0000003ac3414625 in _dl_runtime_resolve () from /lib64/ld-linux-x86-64.so.2
#2  0x0000003ac84b65c7 in std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>) () from /usr/lib64/libstdc++.so.6
#3  0x00000000004010d0 in std::thread::thread<void (*)()>(void (*)()) ()
#4  0x0000000000400e15 in main ()

Kindly help me to resolve this error it seems to be some library is not supportive.

like image 594
Sambhav jain Avatar asked Apr 18 '26 18:04

Sambhav jain


1 Answers

The program looks correct. Compile it with -pthread flag:

g++ -pthread -std=c++11 mythread.cpp
like image 156
Stas Avatar answered Apr 20 '26 08:04

Stas