segmentation fault on joining pthread - c++

I am trying to implement a thread interface class
I am having a problem with join() function, it gives me a segmentation fault
the output:
g++ threadInterface.cpp -lpthread
[murtraja#localhost src]$ ./a.out
Name: Thread # 0
Policy: FIFO
Scope: System
State: Detached
Name: my thread!
Policy: Round Robin
Scope: System
State: Joinable
Now running my thread!
Segmentation fault (core dumped)
What is interesting is that when I call gdb
and set a break at MyThread::run, the prime nos are printed
and I get a message that:
.......
48 is not prime
49 is not prime
0x000000000040141c in main ()
(gdb) s
Single stepping until exit from function main,
which has no line number information.
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bc920a in pthread_join () from /lib64/libpthread.so.0
please refer the code and help me, i am new to threads. BTW, i've removed some code and kept only that is necessary
#include <iostream>
#include<pthread.h>
#include<stdio.h>
#include<cstring>
using namespace std;
class MyThread
{
int policy, state, scope;
char name[35];
char policyName[30];
char stateName[30];
char scopeName[30];
pthread_attr_t attrib;
pthread_t id;
static int count;
void setPrintables();
public:
MyThread(void);
MyThread(char*);
void setPolicy(int);
void setState(int);
void setScope(int);
void setName(char*);
void printDetails();
void loadDefaults();
void run(void *(*function)(void*));
void join();
};
int MyThread::count = 0;
MyThread::MyThread()
{
loadDefaults();
count++;
}
MyThread::MyThread(char* name)
{
loadDefaults();
strcpy(this->name, name);
count++;
}
void MyThread::loadDefaults()
{
pthread_attr_init(&attrib);
pthread_attr_setinheritsched(&attrib, PTHREAD_EXPLICIT_SCHED);
state = PTHREAD_CREATE_JOINABLE;
scope = PTHREAD_SCOPE_PROCESS;
policy = SCHED_OTHER;
sprintf(name, "Thread # %d", count);
}
void MyThread::join()
{
if(state == PTHREAD_CREATE_JOINABLE)
pthread_join(id, NULL);
}
void MyThread::run(void *(*function)(void*))
{
cout<<"Now running "<<name<<endl;
pthread_create(&id, &attrib, function, NULL);
//function(this);
}
void *printFactorials(void*)
{
for(int i=1; i<50; i++)
{
long fact = 1;
for(int j=i; j>=1; j--)
{
fact*=(long)j;
}
cout<<i<<"! = "<<fact<<endl;
}
}
void *printPrimes(void*)
{
for(int i=1; i<50; i++)
{
int c = 0;
for(int j=1; j<=i; j++)
{
if(!(i%j))
c++;
}
if(c==2)
cout<<i<<" is prime"<<endl;
else
cout<<i<<" is not prime"<<endl;
}
}
int main() {
char name[] = "my thread!";
MyThread t1, t2(name);
t1.setPolicy('F');
t1.setState('D');
t1.setScope('P');
t2.setPolicy('R');
t2.setState('J');
t2.setScope('P');
t1.printDetails();
cout<<endl;
t2.printDetails();
//t1.run(printFactorials);
//void* (*f)(void*) = printPrimes;
t2.run(printPrimes);
//t1.join();
t2.join();
return 0;
}
UPDATE:
Using pthread_create(&id, NULL, function, NULL);, gives no seg fault and everything works flawlessly.

The code looks good correct.
However you should be using the compiler option -pthread but just linking to the PThread library with the linker option -lpthread. (https://stackoverflow.com/a/1665110/694576)

Related

Error in passing an element of vector of structures to pthread_create()

I have to create a vector of structures and pass a structure element as the first argument of pthread_create() function.
The code snippet is as follows:
struct example
{
int myint;
pthread_t thread;
};
int main()
{
.............
vector<example> obj;
int count = 1;
while(count < n)
{
int *thread_id = new int(count);
pthread_create(&(obj[count].thread), NULL, worker_routine, thread_id);
count = count+1;
........................
.........................
}
}
I have only included the parts of code that I think has triggered the following error:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7629e4f in __pthread_create_2_1 (newthread=<optimized out>, attr=<optimized out>,
start_routine=<optimized out>, arg=<optimized out>) at pthread_create.c:631
631 pthread_create.c: No such file or directory.
Your problem is with vector. Because in the vector you did not add any element and you are trying to access like below.
obj[count].thread //obj does not have any element
Make changes like below:-
struct example e1, e2, e3,e4,e5;
obj.push_back(e1);
obj.push_back(e2);
obj.push_back(e3);
obj.push_back(e4);
obj.push_back(e5);
while(count < 5)
{
int *thread_id = new int(count);
pthread_create(&(obj[count].thread), NULL, worker_routine, thread_id);
struct example e;
obj.push_back(e);
One more option:-
struct example e1;
vector obj(e1);
int count = 1;
while(count < n)
{
int *thread_id = new int(count);
pthread_create(&(obj[count].thread), NULL, worker_routine, thread_id);
Better use C++ style of multi threading it is much easier:-
struct example
{
int myint;
void operator()()
{
std::cout<<"I am thread :"<<myint<<std::endl;
}
};
int main()
{
struct example exmp;
exmp.myint = 1;
std::thread t1(exmp);
t1.join();
return 0;
}

Segmentation fault in sorting algorithm

so when I run the following code in Xcode, it works, but gives segmentation fault when I run it in terminal and I'm not sure why.
void Word::arrangeWords(char **&words, int*& pages, int size)
{
char *lowest;
int track;
{
for (int i=0;i<size;i++)
{
lowest=new char[30];
strcpy(lowest, words[i]);;
for(int j=i+1;j<size;j++)
{
int compResult=strcmp(lowest, words[j]);
if (compResult>0)
{
strcpy(lowest, words[j]);
track=j;
}
}
std::swap(words[track],words[i]);
std::swap(pages[track],pages[i]);
delete [] lowest;
}
}
}
Thanks in advance
I can't figure out what's causing the segmentation fault but there is a bug in your code. You are not resetting the value of track after the calls to std::swap. I suggest the following changes to the function.
void Word::arrangeWords(char **&words, int*& pages, int size)
{
for (int i=0;i<size;i++)
{
int track = i;
char lowest[30]; // If you know the size of the array to be 30,
// just create an array. Why use new char[30]?
strcpy(lowest, words[i]);;
for(int j=i+1;j<size;j++)
{
int compResult=strcmp(lowest, words[j]);
if (compResult>0)
{
strcpy(lowest, words[j]);
track=j;
}
}
if ( track > i )
{
std::swap(words[track],words[i]);
std::swap(pages[track],pages[i]);
}
}
}

dynamic thread creation in c++

This is my code for multi threading (This is not the actual code but parts of different files at one place where I feel I am doing something wrong)
//main function
Example ExampleObj;
for (int i=0;i<10;i++)
{
pthread_t *service_thread = new pthread_t;
pthread_create(service_thread, NULL,start,&ExampleObj);
}
//start function
void *start(void *a)
{
Example *h = reinterpret_cast<Example *>(a);
h->start1();
return 0;
}
class Example
{
public:
void start1()
{
std::cout <<"I am here \n";
}
};
Code is not giving any error but it's not coming to start1 function as well.
Please let me know if I am creating the threads correctly or not.
If not, then what is the correct way.
There is no code that stops your main() from terminating the process before your worker threads have completed.
main() should look something like:
int main() {
Example ExampleObj;
// Start threads.
pthread_t threads[10];
for(size_t i = 0; i < sizeof threads / sizeof *threads; ++i) {
pthread_create(threads + i, NULL,start,&ExampleObj);
}
// Wait for the threads to terminate.
for(size_t i = 0; i < sizeof threads / sizeof *threads; ++i) {
pthread_join(threads[i], NULL);
}
}

Dining philosophers and mutex initialization

I am trying to solve dining philosophers problem.So I pretty much made entire code but the problem is that I can't initialize monitors(i've made pseudocode which I re-written in c++) so really I can't test the program. Can anyone help me and say what's the issue with initialization of monitor/mutex_init ?
I get error on line 18 and it goes like:
error: ‘int pthread_mutex_init’ redeclared as different kind of symbol
changing it into int pthread_mutex_init(&monitor,NULL); WON'T work !
by adding
int pthread_mutex_init(pthread_mutex_t *monitor, NULL);
I get error: expected identifier before ‘__null’
#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;
char v_filozofi[5]={'O'}; //vizualni prikaz filozofa
int stapic[5]={1}; //stapici za filozofe
int broj[5]; //shema koju sam mora sloziti da imam broj filozofa
pthread_t d_filozofi[5]; //dretve filozofa,philosopher's thread
pthread_cond_t red_uvjeta[5];
pthread_mutex_t monitor; //deklariramo monitor,tj mymutex
int pthread_mutex_init(*monitor,NULL);
void ispisi_stanje(int n){
for(int i = 0; i < 5 ;i++) cout<< v_filozofi[i];
cout<<"("<< n+1 << ")" <<endl;
}
void misliti(int n){
cout<<"Mislim " << endl;
sleep(4);
}
void jesti(int n){
pthread_mutex_lock(&monitor);
v_filozofi[n]='o';
while(stapic[n]==0 || stapic[n+1]%5==0){//gleda ima li lijevi i desni
//stapic na raspolaganju
pthread_cond_wait(&red_uvjeta[n],&monitor);
}
stapic[n] = stapic[(n+1)%5] = 0;
v_filozofi[n] = 'X';
ispisi_stanje(n);
pthread_mutex_unlock(&monitor);
sleep(2);
pthread_mutex_lock(&monitor);
v_filozofi[n] = 'O';
stapic[n] = stapic[(n+1)%5] = 1;
pthread_cond_signal(&red_uvjeta[(n-1)%5]);
pthread_cond_signal(&red_uvjeta[(n+1)%5]);
ispisi_stanje(n);
pthread_mutex_unlock(&monitor);
}
void * filozof(void *n){
int br_fil = *((int *)n);
while(1){
misliti(br_fil);
jesti(br_fil);
}
return 0;
}
//MAIN
int main(){
for(int i=0;i<5;i++){
broj[i] = i;
pthread_cond_init(&red_uvjeta[i],NULL);
}
for(int i=0;i<5;i++){
sleep(1);
pthread_create( &d_filozofi[i],NULL,filozof,&broj[i]);
}
for(int i=0;i<5;i++) pthread_join(d_filozofi[i],NULL);
pthread_mutex_destroy(&monitor);
return 0;
}
remove the line
int pthread_mutex_init(*monitor,NULL);
and instead do
pthread_mutex_init(&monitor,NULL);
at the beginning of your main function. (and check that it returns 0)
As it is you are declaring the function not calling it, and since it's already declared you get an error
This function expects a pointer, and why did you put "int" before the call? I think you confused a prototype (which is unecessary) and an actual call to the function.
int pthread_mutex_init(*monitor,NULL);
So:
pthread_mutex_init(&monitor,NULL);
http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_init.html
once take a look at this one nicely given
http://nitish712.blogspot.in/search/label/mutex
http://nitish712.blogspot.in/2012/09/classical-ipc-problems.html

mpi determinant, CODE: 11 segmentation fault

I'm new to mpi and I want to write a program in C++ that calculates the determinant of a matrix and in the beginning of trying to write it I get this error when trying to compile with mpi compiler.
#include "mpi.h"
#include <iostream>
#include <stdio.h>
#include "/usr/include/malloc.h"
using namespace std;
int matrix[3][3] = {{1,2,3},
{4,5,6},
{7,8,9}};
//**************
int** MakeMatrix (int** oldMatrix,int I,int J,int m,int n)
{
int** newMatrix = (int**)malloc(sizeof(int*)*J);
for(int i=0;i<J;i++)
{
newMatrix[i] = (int*)malloc(sizeof(int)*I);
}
for(int i=0;i<I-1;i++)
for(int j=0;j<J-1;j++)
if(i>=m)
if(j>=n)
{
newMatrix[i][j]=oldMatrix[i+1][j+1];
}
else
{
newMatrix[i][j]=oldMatrix[i+1][j];
}
else
{
newMatrix[i][j]=oldMatrix[i][j];
}
return newMatrix;
}
///////////////////////
int determinan (int** lmatrix,int I,int J)
{
if(I*J==1)
{
return lmatrix[I-1][J-1];
}
int minus = -1;
int sum = 0;
for(int j=0;j<J-1;j++)
{
for(int k=1;k<I+j+1;k++,minus*=minus);
sum += minus*lmatrix[0][j]*determinan(MakeMatrix(lmatrix,I,J,0,j),I-1,J-1);
}
return sum;
}
///*************
int main(int argc,char **argv)
{
//MPI_Init(&argc,&argv);
cout<<determinan((int**)matrix,3,3)<<'\n';
//MPI_Finalize();
return 0;
}
and here is the error message :
===================================================================================
= BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
= EXIT CODE: 11
= CLEANING UP REMAINING PROCESSES
= YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
===================================================================================
YOUR APPLICATION TERMINATED WITH THE EXIT STRING: Segmentation fault (signal 11)
This typically refers to a problem with your application.
Please see the FAQ page for debugging suggestions
I am sure there are multiple problems. The immediate one is the type cast in:
cout<<determinan((int**)matrix,3,3)<<'\n';
^^^^^^^
This isn't a valid cast since matrix isn't an array of pointers.