Resource allocation process is the smallest unit of the thread is the smallest unit of scheduling
Process must be assigned a separate address space, the new data table, stack and data segments
Follow multi-threaded POSIX thread interface, no longer needs the standard library header files pthread.h c
Connection requires libpthread.a--> gcc filename-lpthread
Create a thread
#include <pthread.h> int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn)(void), void *arg) //tidp Thread ID //attr Thread properties, often empty //start_rtn Thread to perform the function //arg start_rtn Parameters
Example;
#include <stdio.h> #include <pthread.h> #include <unistd.h> void *create(void *arg) { int *num; num=(int *)arg; printf("create parameter is %d \n",*num); return (void *)0; } int main(int argc ,char *argv[]) { pthread_t tidp; int error; int test=4; int *attr=&test; error=pthread_create(&tidp,NULL,create,(void *)attr); if(error) { printf("pthread_create is created is not created ... \n"); return -1; } sleep(1); printf("pthread_create is created ...\n"); return 0; }
Terminate a thread in the process of any one thread exit or _exit, the process will terminate the thread exits the normal way:
1 From the start the routine returns
2 terminated by another process
3 pthread_exit function that calls
#include <pthread.h> void pthread_exit(void *rval_ptr) // Terminates the calling thread //rval_ptr The thread exits the return value of the pointer
Example:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void *create(void *arg) { printf("new thread is created ... \n"); return (void *)8; } int main(int argc,char *argv[]) { pthread_t tid; int error; void *temp; error = pthread_create(&tid, NULL, create, NULL); printf("main thread!\n"); if( error ) { printf("thread is not created ... \n"); return -1; } error = pthread_join(tid, &temp); if( error ) { printf("thread is not exit ... \n"); return -2; } printf("thread is exit code %d \n", (int )temp); return 0; }