参考http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SCHEDULING
我正在尝试在 C++ 中创建两个线程并尝试将字符串作为参数传递给Thread Start Routine
. 该Thread Start Routine
参数只能是(void *)
根据定义的类型:
int pthread_create(pthread_t * thread,
const pthread_attr_t * attr,
void * (*start_routine)(void *),
void *arg);
但我得到以下错误:
$ make
g++ -g -Wall Trial.cpp -o Trial
Trial.cpp: In function `int main()':
Trial.cpp:22: error: cannot convert `message1' from type `std::string' to type `void*'
Trial.cpp:23: error: cannot convert `message2' from type `std::string' to type `void*'
Makefile:2: recipe for target `Trial' failed
make: *** [Trial] Error 1
代码是
#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;
}
有什么方法可以string
作为(void *)
参数传递吗?或仅C style strings
可用作多线程参数 - 如链接中的参考代码中所示。