1
votes

I have a function which takes string. Since pthread don't accept string , i make the function's parameter char pointer. Now I want to call that function with pthread_create but i can not do it. Problem arise because of void * i think. I searched it and make some casting but i cannot succeed. How can i fix it so that it can work under g++

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void printString(char *x)
{
    cout << x << endl;
        pthread_exit(NULL);
}

int main ()
{
     pthread_t threads[NUM_THREADS];
     int rc;
     int i;
     string temp = "hello";

  char *bufferG;
  bufferG = new char[temp.size() + 1]; 
  std::copy(temp.begin(), temp.end(), bufferG); 
  bufferG[temp.size()] = '\0'; 

     for( i=0; i < NUM_THREADS; i++ ){
         cout << "main() : creating thread, " << i << endl;
         rc = pthread_create(&threads[i], NULL, printString,  &bufferG ); //(void *) &bufferG also doesn't work
     }
 pthread_exit(NULL);
 }

the error is : thread.cpp: In function ‘int main()’: thread.cpp:27:69: error: invalid conversion from ‘void ()(char)’ to ‘void* ()(void)’ [-fpermissive] /usr/include/pthread.h:225:12: error: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)’ [-fpermissive]

2

2 Answers

3
votes

The argument expected by pthread_create is,

void *(*)(void *)

that is a pointer to function accepting a void pointer and returning a void pointer.

Change your method to have the following signature:

/*static*/ void* printString(void *x) { ... }
1
votes

Ok, try this out, now the main thread joins on children to execute and also instead of printing single character within thread fn, we are now using the whole buffer instead

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void * printString(void *x)
{
    cout << ((char *)x)<< endl;
}

int main ()
{
     pthread_t threads[NUM_THREADS];
     int rc;
     int i;
     string temp = "hello";

  char *bufferG;
  bufferG = new char[temp.size() + 1]; 
  std::copy(temp.begin(), temp.end(), bufferG); 
  bufferG[temp.size()] = '\0'; 


     for( i=0; i < NUM_THREADS; i++ ){
         cout << "main() : creating thread, " << i << endl;
         rc = pthread_create(&threads[i], NULL, printString,  bufferG ); 
     }
    for( i=0; i < NUM_THREADS; i++ ){
     pthread_join(threads[i], NULL);
    }
 pthread_exit(NULL);
 }