引用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 样式字符串
可以用作多线程参数 - 如链接中的引用代码所示。
最佳答案
参数需要是一个指针,你尝试传递一个对象给它。
您有两个选择,要么传递指向 std::string
对象的指针,要么传递指向底层字符串的指针。我推荐第一个:
iret1 = pthread_create(&thread1, NULL, print_message_function, &message1);
然后你必须修改线程函数,否则它会打印指针而不是它指向的字符串:
void* print_message_function(void* ptr)
{
std::string str = *reinterpret_cast<std::string*>(ptr);
std::cout << str << std::endl;
return nullptr;
}
除非需要使用 POSIX 线程,否则我实际上更愿意推荐 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;
}
关于c++ - 传递字符串作为线程启动例程参数 : C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16541477/