#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wimplicit-function-declaration" #include #include #include #include #include #include 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; } #pragma GCC diagnostic pop