Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

concurrent threads: segmentation fault

Status
Not open for further replies.

DCO_81

Member level 1
Joined
Mar 10, 2005
Messages
39
Helped
1
Reputation
2
Reaction score
1
Trophy points
1,288
Location
Germany, south
Activity points
1,657
Hi,

I have this simple concurrent prog with 2 threads. It compiles fine but when I start it I get a segmentation fault. Why?

Code:
#include <pthread.h>
#include <iostream>

using namespace std;

void fun1()
{
	for (int i=0; i < 100; i++)
		cout << "1" << endl;
	pthread_exit(0);
}

void fun2()
{
	for (int i=0; i < 100; i++)
		cout << "2" << endl;
	pthread_exit(0);
}

void concurrent(void (a()), void (b()))
{
	pthread_t pt1, pt2;
	pthread_create(	&pt1,
					NULL,
					(void* (*) (void*)) a,
					NULL);

	pthread_create(	&pt2,
					NULL,
					(void* (*) (void*)) b,
					NULL);
}


void main()
{
	concurrent(fun1, fun2);
}
 

your's pthread_t pt1, pt2 variables are local and when function 'concurent' terminates memory that this variables occupied is freed -, threads that you create tries reference to this variables and this is reason of the segmentation fault.

add at end concurrent(void (a()), void (b())) function

this lines:
pthread_join(pt1, NULL);
pthread_join(pt2, NULL);
 

Thank you for your tip. I also forgot to link -lpthread and add it to my makefile.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top