将字符串传递给pthread函数

时间:2018-10-16 10:28:06

标签: c++ pthreads

我是pthread的初学者,请多多包涵。我正在尝试将字符串传递给thread_routine1函数。它以void指针作为参数。然后,我想将其打印出来。

void *thread_routine1(void *arg1){
    cout << arg1 << endl;
    pthread_exit(NULL);
}

int main ()
{
    pthread_t thread1;
    string t1 = "hello", t2 = "world";
    pthread_create(&thread1, NULL,thread_routine1, (void *) t1);
    pthread_join(thread1, NULL);
    return 0;
}

在pthread_creat函数中,我尝试传递字符串,但是从字符串到void指针的类型转换无效。我知道我可能在多个地方犯了错误,所以我希望得到一些指导。

1 个答案:

答案 0 :(得分:10)

这与pthreads无关。您执行此转换(void *) t1,这实际上是将大锤带入类型系统。

C ++中的字符串不是指针,因此将其强制转换为-并将其视为-只会导致未定义的行为。

这是要避免使用C样式转换的原因之一,因为如果您使用static_cast<void*>(t1)完成了转换,则会得到正确的错误,会责骂您执行不应执行的操作

现在,如果您不能使用std::thread作为其所有抽象,并且必须与pthreads C API竞争,那么方法是传递{{1的 address }}。即

t1

现在您甚至不需要强制转换,因为您正在使用 类型系统。对象指针可以隐式转换为pthread_create(&thread1, NULL,thread_routine1, &t1); 。设计良好的代码不应带有强制转换。它们应该很少出现,并且仅出于充分的理由。此外,强制转换绝对不要仅用于“使其编译”。

哦,别忘了返回您的线程函数。现在您有了充分的理由,并且使用简单的静态强制转换就可以使代码正确:

void*