在Linux中,pthread_join()
函數本身不支持設置超時
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thread_function(void *arg) {
printf("Thread started\n");
sleep(5); // 模擬耗時任務
printf("Thread finished\n");
return NULL;
}
int main() {
pthread_t thread_id;
int rc;
struct timespec timeout;
rc = pthread_create(&thread_id, NULL, thread_function, NULL);
if (rc != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
timeout.tv_sec = 3; // 設置超時時間為3秒
timeout.tv_nsec = 0;
// 使用pthread_timedjoin()等待線程結束,或超時
rc = pthread_timedjoin_np(thread_id, NULL, &timeout);
if (rc == ETIMEDOUT) {
printf("Thread join timed out\n");
} else if (rc != 0) {
perror("pthread_timedjoin_np");
exit(EXIT_FAILURE);
}
printf("Main thread continues\n");
return 0;
}
在這個示例中,我們創建了一個線程,然后使用 pthread_timedjoin_np()
函數等待線程結束,同時設置了一個3秒的超時時間。如果線程在3秒內完成,pthread_timedjoin_np()
將返回0,否則返回 ETIMEDOUT
。