我不知道为什么这不起作用
#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)
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)