Simple pthread! C++

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I have no idea why this doesn't work

#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; } 

The error:

[Description, Resource, Path, Location, Type] initializing argument 3 of 'int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)' threading.cpp threading/src line 24 C/C++ Problem

回答1:

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it 


回答2:

Because the main thread exits.

Put a sleep in the main thread.

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

The POSIX standard does not specify what happens when the main thread exits.
But in most implementations this will cause all spawned threads to die.

So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use 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; } 


回答3:

From the pthread function prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,     void *(*start_routine)(void*), void *arg); 

The function passed to pthread_create must have a prototype of

void* name(void *arg) 


回答4:

This worked for me:

#include <iostream> #include <pthread.h> using namespace std;  void* print_message(void*) {      cout << "Threading\n"; }  int main() {      pthread_t t1;      pthread_create(&t1, NULL, &print_message, NULL);     cout << "Hello";      // Optional.     void* result;     pthread_join(t1,&result);     // :~      return 0; } 


回答5:

When compiling with G++, remember to put the -lpthread flag :)



回答6:

Linkage. Try this:

extern "C" void *print_message() {...



文章来源: Simple pthread! C++
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!