Подтвердить что ты не робот

Простой pthread! С++

Я понятия не имею, почему это не работает.

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

Ошибка:

[Описание, ресурс, путь, местоположение, тип] аргумент инициализации 3 of 'int pthread_create (pthread_t *, const pthread_attr_t *, void * (*) (void *), void *) 'threading.cpp threading/src line 24 C/С++ Проблема

4b9b3361

Ответ 1

Вы должны объявить главный поток как:

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

Ответ 2

Поскольку основной поток завершается.

Поместите спать в основной поток.

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

return 0;

В стандарте 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;
}

Ответ 3

Из прототипа функции pthread:

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

Функция, переданная в pthread_create, должна иметь прототип

void* name(void *arg)

Ответ 4

Это сработало для меня:

#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

Связь. Попробуйте следующее:

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

Ответ 6

При компиляции с g++ не забудьте поставить флаг -lpthread:)