Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
pthread_join is a function in the POSIX threads library (pthread) that allows a calling thread to wait for the termination of a specific thread. This function is important in multi-threaded programming as it enables synchronization and coordination between threads. In Linux, pthread_join is widely used to ensure that the main thread waits for the completion of child threads before proceeding further.
To use pthread_join in Linux, you need to include the pthread.h header file and link against the pthread library using the -pthread flag during compilation. This ensures that the necessary pthread functions and data types are available.
Examples:
Example 1: Basic usage of pthread_join
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
printf("Hello from thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
pthread_join(thread, NULL);
printf("Thread joined!\n");
return 0;
}
In this example, we create a new thread using pthread_create and pass it the function thread_func as the thread's entry point. The main thread then waits for the completion of the created thread using pthread_join. Once the thread is joined, the main thread continues its execution.
Example 2: Passing and receiving data from the thread using pthread_join
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
int* num = (int*)arg;
printf("Received number: %d\n", *num);
*num += 10;
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int data = 42;
pthread_create(&thread, NULL, thread_func, &data);
pthread_join(thread, NULL);
printf("Modified number: %d\n", data);
return 0;
}
In this example, we pass an integer value to the thread through the arg parameter of pthread_create. Inside the thread_func, we cast the argument back to an integer pointer and manipulate the value. After joining the thread, the main thread can access the modified value.