}
После запуска вы получите следующий вывод:
$ cc -D_REENTRANT thread4.с -о thread4 -lpthread
$ ./thread4
Input some text. Enter 'end' to finish
Whit
You input 4 characters
The Crow Road
You input 13 characters
end
Waiting for thread to finish...
Thread joined
Как это работает
Вы начинаете с объявления мьютекса вашей рабочей области и на сей раз дополнительной переменной time_to_exit:
pthread_mutex_t work_mutex; /* защищает work_area и time_to_exit */
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit = 0;
Далее инициализируется мьютекс:
res = pthread_mutex_init(&work_mutex, NULL);
if (res != 0) {
perror("Mutex initialization failed");
exit(EXIT_FAILURE);
}
Затем запускается новый поток. Далее приведен код, выполняемый в функции потока:
pthread_mutex_lock(&work_mutex);
while(strncmp("end", work_area, 3) != 0) {
printf("You input id characters\n", strlen(work_area)-1);
work_area[0] = '\0';
pthread_mutex_unlock(&work_mutex);