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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.