clab/c/pthreadex5.c
2024-06-28 09:09:03 +01:00

42 lines
996 B
C

#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
void *thread_func(void *arg) {
// Sleep for a random amount of time between 1 and 5 seconds
int sleep_time = 1 + rand() % 5;
sleep(sleep_time);
return arg;
}
int main() {
pthread_t thread;
int thread_arg = 100;
// Create the thread
pthread_create(&thread, NULL, thread_func, &thread_arg);
// Set up a timeout for the pthread_timedjoin_np function
struct timespec timeout;
clock_gettime(CLOCK_REALTIME, &timeout);
timeout.tv_sec += 3; // Wait for at most 3 seconds
void *result;
int ret;
// Wait for the thread to finish, with a timeout
ret = pthread_timedjoin_np(thread, &result, &timeout);
if (ret == 0) {
printf("Thread finished within the timeout\n");
} else if (ret == ETIMEDOUT) {
printf("Timed out waiting for thread to finish\n");
} else {
printf("Error waiting for thread to finish %d\n", ret);
}
return 0;
}