Answer the question
In order to leave comments, you need to log in
POSIX threads + usleep - why doesn't it work?
I emulate the work of the ticket terminal, customers appear at a random time, ask about the availability of tickets during a random period of time and then buy also during a random period of time. Random for each operation should be different, i.e. I generate the time in microseconds, display the description of the current operation, and put the thread to sleep with usleep for that time. BUT the thread falls asleep for as long as it wants, and not for the generated period of time. For example, it generated 9.3 seconds, and wakes up somewhere after 3. What's wrong?
// функция, содержащая действия потока-клиента
void *customer_function(void *arg)
{
// устанавливаем состояние завершения на немедленное, при получении запроса
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
int my_id;
unsigned int ssss;
srand(time(NULL));
...
printf("\n\nCustomer has joined the queue");
// захват мьютекса
pthread_mutex_lock(&mutex);
...
// left и right целые, устанавливаются при запуске из ключей, в секундах, например от left == 2 до right == 5 сек
ssss = (rand() % ((right - left) * 10 + 1) + left * 10);
printf("\n\nCustomer #%d is asking about the tickets... Time to sleep = %.1lf secs", my_id, ssss / 10.0);
// задержка работы потока на рандомное число секунд от left до right секунд
usleep(ssss * 100000);
....
ssss = (rand() % ((right - left) * 10 + 1) + left * 10);
printf("\n\nCustomer #%d is buying the tickets... Time to sleep = %.1lf secs", my_id, ssss / 10.0);
// задержка работы потока на рандомное число секунд от left до right секунд
usleep(ssss * 100000);
....
// после покупки выводим инфо о купленных / заказанных билетах
printf("\n\nCustomer #%d 's purchase result:\n", my_id);
...
// освобождение мьютекса
pthread_mutex_unlock(&mutex);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question