multithreading - Passing string as Thread start routine parameter : C++ -
referring http://www.yolinux.com/tutorials/linuxtutorialposixthreads.html#scheduling
i trying create 2 threads in c++ , trying pass string parameter thread start routine. thread start routine parameter can (void *) type per definition:
int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg); but below error:
$ make g++ -g -wall trial.cpp -o trial trial.cpp: in function `int main()': trial.cpp:22: error: cannot convert `message1' type `std::string' type `void*' trial.cpp:23: error: cannot convert `message2' type `std::string' type `void*' makefile:2: recipe target `trial' failed make: *** [trial] error 1 the code is
#include <iostream> #include <pthread.h> #include <string> using namespace std; void *print_message_function( void *ptr ); int main() { pthread_t thread1, thread2; string message1 = "thread 1"; string message2 = "thread 2"; int iret1, iret2; iret1 = pthread_create( &thread1, null, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, null, print_message_function, (void*) message2); pthread_join( thread1, null); pthread_join( thread2, null); cout << "thread 1 returns: " << iret1 << endl; cout << "thread 2 returns: " << iret2 << endl; return 0; } void *print_message_function( void *ptr ) { cout << endl << ptr << endl; //return 0; } is there way pass string (void *) parameter ? or c style strings can used multithreading parameters - given in reference code @ link.
the argument needs pointer, , try pass object it.
you have 2 choices, either pass pointer std::string object, or pass pointer underlying string. recommend first:
iret1 = pthread_create(&thread1, null, print_message_function, &message1); then have modify thread function, otherwise print pointer , not string points to:
void* print_message_function(void* ptr) { std::string str = *reinterpret_cast<std::string*>(ptr); std::cout << str << std::endl; return nullptr; } unless it's requirement use posix threads, rather recommend threading functionality in c++ standard library:
#include <iostream> #include <string> #include <thread> void print_message_function(const std::string& msg); int main() { std::string message1 = "thread 1"; std::string message2 = "thread 2"; std::thread thread1(print_message_function, std::cref(message1)); std::thread thread2(print_message_function, std::cref(message2)); thread1.join(); thread2.join(); } void print_message_function(const std:string& msg) { std::cout << msg << std::endl; }
Comments
Post a Comment