0

Всем привет. Прошу помощи.

Задание:

Задается число - threads. Главная нить создает threads нитей, каждая из которых печатает "hello world". После того, как эти нити завершатся, главная нить печатает "goodbye world". Используемые функции: pthread_create; pthread_exit; pthread_join

Мой код:

void *print_hello_world(void *tid)
{
    printf("Hello world %d\n", tid);
    pthread_exit(NULL);
}

int main(void)
{

int a;
int i;
int status;
cin >> a;
pthread_t threads[a];

for (i = 1; i <= a; i++)
{

    status = pthread_create(&threads[i], NULL, print_hello_world, (void *)i);

    if (status != 0)
    {
        printf("Error %d\n", status);
        exit(-1);
    }
}
printf ("goodbye")
exit(NULL);
}

На выходе:

Hello world 3

Hello world 1

goodbyeHello world 4

Hello world 5

Hello world 2

Я не могу понять где здесь можно реализовать "pthread_join" и почему такая беда с выводом.

1

1 ответ 1

1

Так как вы не ожидаете завершения потока , вывод может быть в любой последовательности, но если подождать завершения то вывод будет последовательный

 for (i = 1; i <= a; i++)
{

    status = pthread_create(&threads[i], NULL, print_hello_world, (void *)i);

    if (status != 0)
    {
        printf("Error %d\n", status);
        exit(-1);
    }
    pthread_join(threads[i],NULL);

}
1
  • Спасибо. Теперь вывод в нужном порядке.
    – John
    20 апр 2016 в 4:20

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.