dimanche 26 novembre 2017

c++ - Passing vector to thread

I am getting error like below on passing vector via pthread_create as given below.

#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;

void foo(void *a)
{
  vector <int> b = (vector <int>*)a;

  for(int i=0; i<b.size(); i++)
  {
        std::cout<<b[i];
  }
  return NULL;
}

void bar(int x)
{
  std::cout<<"bar";
}

int main()
{
  pthread_t thr;
  std::vector <int> a = {1,2,3};
  pthread_create(&thr, NULL, &foo, (void *)&a);
  pthread_join(thr,NULL);
  return 0;

Error messages :

threadeg.cpp: In function ‘void foo(void*)’:
threadeg.cpp:9:35: error: conversion from ‘std::vector<int>*’ to non-scalar type ‘std::vector<int>’ requested
   vector <int> b = (vector <int>*)a;

threadeg.cpp:16:10: error: return-statement with a value, in function returning 'void' [-fpermissive]
   return NULL;
          ^
threadeg.cpp: In function ‘int main()’:
threadeg.cpp:28:46: error: invalid conversion from ‘void (*)(void*)’ to ‘void* (*)(void*)’ [-fpermissive]
   pthread_create(&thr, NULL, &foo, (void *)&a);

/usr/include/pthread.h:244:12: error:   initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’ [-fpermissive]
 extern int pthread_create (pthread_t *__restrict __newthread,

I am new to threads and I m unable to figure out what is going wrong. Can anyone point out the problem and suggest a solution?

Aucun commentaire:

Enregistrer un commentaire