[Cpp] # include <stdio. h>
# Include <pthread. h>
Void thread (void ){
Int I;
Printf ("This is a thread. \ n ");
Pthread_exit (NULL );
}
Int main (void ){
Pthread_t id;
Int ret;
Ret = pthread_create (& id, NULL, (void *) thread, NULL );
If (ret! = 0 ){
Printf ("Create pthread error! \ N ");
Exit (1 );
}
Int I;
Printf ("This is the main process. \ n ");
Pthread_join (id, NULL );
Return 0;
}
# Include <stdio. h>
# Include <pthread. h>
Void thread (void ){
Int I;
Printf ("This is a thread. \ n ");
Pthread_exit (NULL );
}
Int main (void ){
Pthread_t id;
Int ret;
Ret = pthread_create (& id, NULL, (void *) thread, NULL );
If (ret! = 0 ){
Printf ("Create pthread error! \ N ");
Exit (1 );
}
Int I;
Printf ("This is the main process. \ n ");
Pthread_join (id, NULL );
Return 0;
}
Function Description:
Int pthread_create (pthread_t * restrict tidp, const pthread_attr_t * restrict_attr, void * (* start_rtn) (void *), void * restrict arg );
This function accepts four parameters: pointer to the thread identifier, thread attribute, start address of the thread running function, and parameters of the running function. The second and fourth parameters are both NULL and may be modified later.
If this function is successfully executed, 0 is returned; otherwise, an error number is returned.
Pthread_t is used to declare the thread id.
Int pthread_join (pthread_t thread, void ** retval );
This function waits for the thread to end in a blocked way. When the function returns, the resources of the waiting thread are reclaimed. If the process has ended, the function returns immediately. This indicates that the main function is exited only after the threads are finished. If this function is not added, the main function stops executing its own code program, it does not matter whether the thread is running or not.
The first parameter is the thread ID, which identifies a unique thread. The second parameter is a user-defined pointer used to store the return values of the waiting thread.
If this function is successfully executed, 0 is returned. Otherwise, the error number is returned.
Note:-lpthread must be added during compilation. If gdb debugging is allowed,-g must be added.
Gcc-o homework1 homework1.c-lpthread