[英]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. 我必须创建一个结构向量,并将结构元素作为pthread_create()函数的第一个参数传递。
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; 另一个选择:-结构示例e1; vector obj(e1);
向量obj(e1); int count = 1;
int count = 1; while(count < n) { int *thread_id = new int(count);
while(count <n){int * thread_id = new int(count);
pthread_create(&(obj[count].thread), NULL, worker_routine, thread_id); pthread_create(&(obj(count] .thread),NULL,worker_routine,thread_id);
Better use C++ style of multi threading it is much easier:- 更好地使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.