#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h>//include threads Library # include <string.h>void *thread_function (void *arg); Define thread function prototype//char message[] = "Thread_test"; Defines a common memory space Char Message[100];int main () {int res; Used to save the return value of the creation thread pthread_t a_thread; Used to save information such as thread identifiers void *thread_result; The return value for the receive thread end is the res = Pthread_create (&a_thread, NULL, thread_function, (void *) message); Create thread if (res! = 0) {//Determine if creation has error perror ("Thread creation failed"); Exit (Exit_failure); } printf ("Wait for thread to end ... \ n"); res = PTHRead_join (A_thread, &thread_result); Wait for thread to end if (res! = 0) {//To determine if the end thread is wrong False perror ("Wait for Thread end failed"); Exit (Exit_failure); } printf ("Thread has ended, return value:%s\n", (char *) thread_result); The output thread returns the message printf ("Value of message:%s\n", message); Output the value of the public memory space exit (exit_success);} void *thread_function (void *arg) {//define thread function details pri NTF ("Thread is running, parameter is:%s\n", (char *) arg); Parameters of the output thread sleep (3); Causes the thread to hibernate for 3 seconds strcpy (message, "thread modification"); Modifies the value of the common memory space pthread_exit ("Thread Execution Complete"); End Thread}
Basic operation of thread, create thread, end thread, new thread share variable with original thread