clab/c/pthreadex4.c

34 lines
731 B
C

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *thread_func(void *data) {
sleep(1);
printf("Hello from the new thread!\n");
return NULL;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, NULL, thread_func, NULL);
if (result != 0) {
printf("Error creating thread: %d\n", result);
return 1;
}
while (1) {
result = pthread_tryjoin_np(thread, NULL);
if (result == 0) {
// thread has finished
break;
}
printf("Waiting for thread to finish...\n");
sleep(1);
}
printf("Hello from the main thread!\n");
return 0;
}
#pragma GCC diagnostic pop