POSIX line Libraries
Thread-related functions make up a complete series, with most functions beginning with the name "Pthread_", to use these libraries, by introducing header <pthread.h>, and by using the "-lpthread" of the compiler command when linking these thread function libraries Options [Ubuntu Series system needs to add "-pthread" option instead of "-lpthread", such as Ubuntu 14.04 version, Deepin Ubuntu etc.]
1.pthread_create
int pthread_create (pthread_t *restrict thread,const pthread_attr_t *restrict attr,void * (*start_routine) (void*), void * Restrict Arg);
Create a new thread
Parameters
Thread: Threads ID
attr: Set the properties of a thread, generally set to NULL to use the default properties
start_routine: is a function address, the function to execute after the thread starts
ARG: Arguments passed to the thread start function
Return value: Successful return 0, failure return error code ;
Attached-posix error Check
UNIX Traditional functions: Successfully returned 0, failed to return 1, and set global variable errno to specify the error type. However, the Pthreads function does not set the global variable errno (while most of the other POSIX functions will set the errno). Instead, the error code is returned by the return value ;
Pthreads also provides a errno variable within the thread , with a errno value for each thread to support other code that uses errno. For errors in the Pthreads function, it is recommended that the return value be determined because reading the return value is less expensive than reading the errno variable inside the thread !
/** Practice: New error checking with error exit Function **/inline void Err_check (const std::string &msg, int retno) { if (Retno! = 0) Err_exit (ms g, Retno);} inline void Err_exit (const std::string &msg, int retno) { std::cerr << msg << ":" << strerror (re TNO) << Endl; Exit (exit_failure);}
2.pthread_exit
void Pthread_exit (void *value_ptr);
Thread termination
Value_ptr: Point to the return value of the thread; Note:value_ptr cannot point to a local variable .
3.pthread_join
int Pthread_join (pthread_t thread, void **value_ptr);
Wait for thread to end
Value_ptr: It points to a pointer, which points to the return value of the thread (the return value of the user gets the thread)
/** Example: Waiting for a thread to exit **/void *thread_rotine (void *args) {for (int i = 0; i < ++i) { printf ("B"); Fflush (stdout); Usleep (); } Pthread_exit (NULL);} int main () { pthread_t thread; int ret = pthread_create (&thread, NULL, thread_rotine, NULL); Err_check ("Pthread_create", ret); for (int i = 0; i < ++i) { printf ("A"); Fflush (stdout); Usleep (); } ret = Pthread_join (thread, NULL); Err_check ("Pthread_join", ret); Putchar (' \ n '); return 0;}
4.pthread_self
pthread_t pthread_self (void);
Return thread ID
/** Example: Master thread and Child thread pass data **/typedef struct _student{ char name[20]; unsigned int age;} Student;void *threadfunction (void *args) { cout << "in Thread:" << pthread_self () << Endl; Student tmp = * (Student *) (args); cout << "Name:" << tmp.name << Endl; cout << "Age:" << tmp.age << Endl; Pthread_exit (NULL);} int main () { Student Student = {"Xiaofang", +}; pthread_t thread; Start Create and start thread pthread_create (&thread,null,threadfunction,&student); Wait for thread to end Pthread_join (thread,null); return 0;}
5.pthread_cancel
int Pthread_cancel (pthread_t thread);
To cancel a thread in execution
6.pthread_detach
int Pthread_detach (pthread_t thread);
Detach a thread-if the main thread does not end at the end of the newly created threads and does not call Pthread_join, a zombie thread is generated, and the second problem can be resolved by setting the thread as detached (detach);
Summary: Process VS. Thread
Process (pid_t) |
Thread (pthread_t) |
Fork |
Pthread_create |
Waitpit |
Pthread_join/pthread_detach |
Kill |
Pthread_cancel |
Pid |
Pthead_self |
Exit/return |
Pthread_exit/return |
Zombie process ( No functions such as wait/waitpid are called) |
Zombie thread (no call to Pthread_join/pthread_detach) |
/** the resolution of the concurrent ECHO server to a multi-threaded form of attention to thread racing issues **/void echo_server (int clientsocket); void *thread_routine (void *arg); int main () {int SOCKFD = socket (af_inet,sock_stream,0); if (SOCKFD = =-1) err_exit ("Socket error"); int optval = 1; if (setsockopt (sockfd,sol_socket,so_reuseaddr,&optval,sizeof (optval)) = =-1) err_exit ("setsockopt error"); struct sockaddr_in serveraddr; serveraddr.sin_family = af_inet; Serveraddr.sin_port = htons (8002); SERVERADDR.SIN_ADDR.S_ADDR = Inaddr_any; Bind any one IP address of the machine if (bind (SOCKFD, struct sockaddr *) &serveraddr,sizeof (serveraddr)) = =-1) err_exit ("Bind err or "); if (listen (sockfd,somaxconn) = =-1) err_exit ("Listen error"); while (true) {int peersockfd = accept (SOCKFD, NULL, NULL); if (PEERSOCKFD = =-1) err_exit ("Accept error"); pthread_t Tid; /** Note: The following usage may produce a "race problem" when another connection fast-read fast arrives, the content of the PEERSOCKFD changes, the newly created thread has not taken the value away, and the thread reads not We want the thread to read the value of int ret = Pthread_create (&tid, NULL, Thread_routine, (void *) &PEERSOCKFD); **///Solution: Create a piece of memory int *p = new int (PEERSOCKFD) for each link; int ret = Pthread_create (&tid, NULL, Thread_routine, p); if (ret! = 0) err_thread ("Pthread_create error", ret); } close (SOCKFD);}
void *thread _routine (void *args) {//threads are set to detach state to avoid zombie thread Pthread_detach (pthread_self ()); int PEERSOCKFD = * (int *) args; After the value is taken, the memory is freed out of the delete (int *) args; Echo_server (PEERSOCKFD); cout << "Thread" << pthread_self () << "exiting ..." << Endl; Pthread_exit (NULL);} void Echo_server (int clientsocket) {char Buf[bufsiz] = {0}; int readbytes; while ((readbytes = Read (Clientsocket, buf, sizeof (BUF))) >= 0) {if (readbytes = = 0) {cer R << "Client Connect closed" << Endl; Break } if (Write (Clientsocket, buf, readbytes) = =-1) {cerr << "server thread write error" < < Endl; Break } cout << buf; Bzero (buf, sizeof (BUF)); }}
Its full source code:download.csdn.net/detail/hanqing280441589/8440763
Linux multithreaded Practice (2)--Thread Basic API