简单的pthread!C++

Ang*_*.47 21 c++ pthreads

我不知道为什么这不起作用

#include <iostream>
#include <pthread.h>
using namespace std;

void *print_message(){

    cout << "Threading\n";
}



int main() {

    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

[描述,资源,路径,位置,类型]初始化'int pthread_create的参数3(pthread_t*,const pthread_attr_t*,void*(*)(void*),void*)'threading.cpp threading/src line 24 C/C++问题

Sam*_*ell 36

您应该将主线声明为:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案.最初的问题是错误格式化的,所以他得错误的错误消息(缺少几个星号,它们被视为斜体标记).我现在修好了. (3认同)
  • 你想要什么*并不重要,`pthread_create`接受一个指向一个函数的指针,该函数将`void*`作为参数并返回`void*`.这是十年来定义的API.:)你不是被迫使用它. (3认同)
  • ^ == print_message(NULL) 的答案 (2认同)

Mar*_*ork 18

因为主线程退出.

在主线程中睡一觉.

cout << "Hello";
sleep(1);

return 0;
Run Code Online (Sandbox Code Playgroud)

POSIX标准没有规定主线程退出时会发生什么.
但在大多数实现中,这将导致所有生成的线程死亡.

因此,在主线程中,您应该在退出之前等待线程死亡.在这种情况下,最简单的解决方案就是睡眠并为其他线程提供执行机会.在实际代码中,您将使用pthread_join();

#include <iostream>
#include <pthread.h>
using namespace std;

#if defined(__cplusplus)
extern "C"
#endif
void *print_message(void*)
{
    cout << "Threading\n";
}



int main() 
{
    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    void* result;
    pthread_join(t1,&result);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我不得不碰到你,即使我认为你要超越我的"较小"答案大声笑 (2认同)