c++ - 传递字符串作为线程启动例程参数 : C++

标签 c++ multithreading

引用http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SCHEDULING

我试图在 C++ 中创建两个线程,并试图将字符串作为参数传递给 Thread Start RoutineThread 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/

相关文章:

c++ - 如何在 C++ 的 Qt Creator 中向 TableView 添加自定义对象?

c++ - 在 linux 上编译 windows 64 程序时出现问题 - headers

c++ - 如何用不同数量的默认参数包装一个函数,使其只有一个参数?

java - 让线程无限期等待

c++ - 如何并行化这个 for 循环以快速将 YUV422 转换为 RGB888?

c++ - 无法将 char[33] 转换为 LPCTSTR,或者如果我将类型转换为 LPCTSTR,则无法获得所需的结果

c++ - 没有返回类型的静态函数可以在 Windows 上通过编译但在 Linux 上不能

c# - 我应该使用线程还是任务 - 多客户端模拟

java - 设置 HashMap 线程安全吗?

c# - C#中长时间运行任务的进度条