繁体   English   中英

将结构向量的元素传递给pthread_create()时出错

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

我必须创建一个结构向量,并将结构元素作为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.

你的问题是矢量。 因为在向量中您没有添加任何元素,所以您尝试按如下方式访问。

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);

另一个选择:-结构示例e1; 向量obj(e1); int count = 1; while(count <n){int * thread_id = new int(count);
pthread_create(&(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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM