Категории
Самые читаемые
ChitatKnigi.com » 🟢Компьютеры и Интернет » Интернет » Основы программирования в Linux - Мэтью Нейл

Основы программирования в Linux - Мэтью Нейл

Читать онлайн Основы программирования в Linux - Мэтью Нейл
1 ... 222 223 224 225 226 227 228 229 230 ... 324
Перейти на страницу:

Шрифт:

-
+

Интервал:

-
+

Закладка:

Сделать

  perror("Thread pthread_setcancelstate failed");

  exit(EXIT_FAILURE);

 }

 res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);

 if (res != 0) {

  perror{"Thread pthread_setcanceltype failed");

  exit(EXIT_FAILURE);

 }

 printf("thread_function is runningn");

 for(i = 0; i < 10; i++) {

  printf("Thread is still running (%d)...n", i);

  sleep(1);

 }

 pthread_exit(0);

}

Когда вы выполните эту программу, то увидите следующий вывод, демонстрирующий отмену потока:

$ <b>./thread7</b>

thread_function is running

Thread is still running (0)...

Thread is still running (1)...

Thread is still running (2)...

Canceling thread...

Waiting for thread to finish...

$

Как это работает

После того как новый поток был создан обычным способом, основной поток засыпает (чтобы дать новому потоку время для запуска) и затем отправляет запрос на отмену потока.

sleep(3);

printf(&quot;Cancelling thread...n&quot;);

res = pthread_cancel(a_thread);

if (res != 0) {

 perror(&quot;Thread cancelation failed&quot;);

 exit(EXIT_FAILURE);

}

В созданном потоке вы сначала задаете состояние отмены, чтобы разрешить отмену потока:

res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

if (res != 0) {

 perror(&quot;Thread pthread_setcancelstate failed&quot;);

 exit(EXIT_FAILURE);

}

Далее вы задаете тип отмены PTHREAD_CANCEL_DEFERRED:

res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);

if (res != 0) {

 perror(&quot;Thread pthread_setcanceltype failed&quot;);

 exit(EXIT_FAILURE);

}

И в конце поток ждет отмену:

for (i = 0; i &lt; 10; i++) {

 printf(&quot;Thread is still running (%d)...n&quot;, i);

 sleep(1);

}

Потоки в изобилии

До настоящего момента у нас всегда был обычный поток исполнения программы, создающий еще только один поток. Тем не менее мы не хотим, чтобы вы думали, что можно создать только один дополнительный поток (упражнение 12.8).

Упражнение 12.8. Много потоков

В заключительном примере этой главы thread8.c мы покажем, как создать несколько потоков в одной и той же программе и затем собрать их снова в последовательности, отличающейся от порядка их создания.

#include &lt;stdio.h&gt;

#include &lt;unistd.h&gt;

#include &lt;stdlib.h&gt;

#include &lt;pthread.h&gt;

#define NUM_THREADS 6

void *thread_function(void *arg);

int main() {

 int res;

 pthread_t a_thread[NUM_THREADS];

 void *thread_result;

 int lots_of_threads;

 for (lots_of_threads = 0; lots_of_threads &lt; NUM_THREADS; lots_of_threads++) {

  res = pthread_create(&amp;(a_thread[lots_of_threads]), NULL, thread_function, (void*)&amp;lots_of_threads);

  if (res != 0) {

   perror(&quot;Thread creation failed&quot;);

   exit(EXIT_FAILURE);

  }

  sleep(1);

 }

 printf(&quot;Waiting for threads' to finish...n&quot;);

 for(lots of_threads = NUM_THREADS - 1; lots_of_threads &gt;= 0; lots_of_threads--) {

  res = pthread_join(a_thread[lots_of_threads], &amp;thread_result);

  if (res == 0) {

   printf(&quot;Picked up a threadn&quot;);

  } else {

   perror(&quot;pthread_join failed&quot;);

  }

 }

 printf(&quot;All donen&quot;);

 exit(EXIT_SUCCESS);

}

void *thread_function(void *arg) {

 int my_number = *(int*)arg;

 int rand_num;

 printf(&quot;thread_function is running. Argument was %dn&quot;, my_number);

 rand_num = 1 + (int)(9.0*rand() / (RAND_MAX+1.0));

 sleep(rand_num);

 printf(&quot;Bye from %dn&quot;, my_number);

 pthread_exit(NULL);

}

Выполнив эту программу, вы получите следующий вывод:

$ <b>./thread8</b>

thread_function is running. Argument was 0

1 ... 222 223 224 225 226 227 228 229 230 ... 324
Перейти на страницу:
Открыть боковую панель
Комментарии
Галина
Галина 05.11.2025 - 22:53
Красивая история. Вселяет веру в добро !
Женя
Женя 05.11.2025 - 12:27
Ну, конечно, закрутили) Санта Барбара отдыхает
Viola
Viola 04.11.2025 - 22:45
Больше подойдёт для подростков.
Таня
Таня 02.11.2025 - 01:03
А продолжение? Уверенна, что оно должно быть
Уля
Уля 26.10.2025 - 00:40
У богатых свои причуды. С удовольствием буду читать продолжение