我必须创建一个结构向量并传递一个结构元素作为pthread_create()函数的第一个参数。
代码段如下:
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;
........................
.........................
}
}
我只包含了我认为触发了以下错误的代码部分:
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.
答案 0 :(得分:0)
你的问题是矢量。因为在向量中您没有添加任何元素,并且您尝试访问如下所示。
obj[count].thread //obj does not have any element
进行如下更改: -
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);
还有一个选择: -
struct example e1;
vector obj(e1);
int count = 1;
而(计数&lt; n)
{
int * thread_id = new int(count);
pthread_create(&amp;(obj [count] .thread),NULL,worker_routine,thread_id);
更好地使用C ++风格的多线程更容易: -
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;
}