POSIX multithreading--Introduction to basic thread management functions

Source: Internet
Author: User
Tags posix

POSIX basic several thread management functions are shown in the following table:------------------------------------------------------------------------------------------                       POSIX functions                                                             Description-------------------------------------------------------------------------------------------                     Pthread_ create                                    Create a thread                      pthread_self                                          Find your own thread id                     pthread_equal                                       test whether 2 thread IDs are equal                      pthread_detach                                    set up threads to free up resources                      pthread_join                                           waiting for a thread                      pthread_cancel                                      Terminate another thread                      pthread_exit                                           quit a thread without exiting the process                      pthread_kill                                             sends a signal to the thread-------------------------------------------------------------------------------------------   (1) thread ID, get, and compare POSIX threads are referenced by an ID of pthread_t type. The thread can get its own thread ID by calling the pthread_self  () function, and there is no error defining pthread_self .  ========================== Overview: #include <pthread.h>                      pthread_t   Pthread_ self  (void);    ==========================  because pthread_t   may be a structure, it cannot be directly compared by = =. Here you can use the function pthread_equal () to compare thread IDs for equality, there are no pthread_equal errors, if two thread IDs are equal, return a non-0 value, otherwise return 0. ======================== ==================== Overview: #include <pthread.h>                      int   Pthread_equal (pthread_t  T1, pthread_t  T2);   ============================================  (2) Create thread can use Pthread_ Create () creates a thread. The threads created by POSIX pthread_create () can be run directly without requiring a separate startup operation.  ========================================== Overview: #include <pthread.h>
int Pthread_create (pthread_t *restrictThread,
Const pthread_attr_t *restrict attr,
void * (*start_routine) (void *),
void *restrict arg); ========================================== in the above function, thread points to the newly created thread ID, and the parameter attr represents a Property object that encapsulates the various properties of the thread (such as stack size, dispatch, etc.). Later), if attr is null, the default property is used to create it, and the third parameterStart_routine is the name of the function called when the thread starts executing, and the fourth argument arg pointer to the data is the start_routine parameter. If successful, the function returns 0, otherwise a non-0 error code is returned.  the code in the following example is to create 10 threads in a row, and the code executing in the thread is only printing its own thread ID, and the owning process ID: 
#include <pthread.h>#include<stdio.h>void*print_thread (int*i) {fprintf (stderr,"number:%d,pid:%d,tid:%lld.\n", *i,getpid (), (Long Long) pthread_self ()); returnNULL;} intMainintargcChar*argv[]) {pthread_t tids[Ten]; inti; for(i=0;i<Ten; i++) {  if(Pthread_create (&tids[i],null,print_thread,&i) ==-1) {fprintf (stderr,"\nerror:fail to creat thread."); Tids[i]=pthread_self (); } } return 0;}

execution result:
[email protected] : ~$ ./thr
Number:0,pid:5579,tid : 3085089680.
number:1,pid:5579,tid:3076696976.
number:2,pid:5579,tid:3068304272.
number:3,pid:5579,tid:3059911568.
number:4,pid:5579,tid:3051518864.
number:5,pid:5579,tid:3043126160.
number:6,pid:5579,tid:3034733456.
number:7,pid:5579,tid:3026340752.
number:8,pid:5579,tid:3017948048.
number:9,pid:5579,tid:3009555344.
[email protected] :~$(3) thread separation (detach) and join (join) in general, the thread will not release its resources when exiting, if the thread is detached, that is, the thread is called Pthread_detach (tid) or the thread itself calls Pthread_detach ( Pthread_self ()), which sets the internal options of the thread to indicate that the storage space can be reclaimed after the thread exits, the detached thread will not report their state when exiting. If the thread is not detached, then it can be bonded (join), pthread_join and process-level functions wait_pid very similar, the function suspends the calling thread until the target thread specified by the first parameter terminates. If the Create thread calls Pthread_join () on a child thread, the resource is recycled after the process exits after it exits. The parameter value_ptr is a pointer to the return value, which is the destination thread return or passed to Pthread_exit (). To prevent memory leaks, long-running threads should eventually call Pthread_join () or Pthread_detach () for each thread. =========================================== Overview:#include <pthread.h>int Pthread_join (pthread_t th, void **value_ptr)
int Pthread_detach (pthread_t thread)
=========================================== The following sample program demonstrates the relationship between Pthread_detach and Pthread_join. (1) The sub-thread will detach itself, this situation is not allowed to join the process.
#include <pthread.h>#include<stdio.h>void*print_thread (void*ptr) { if(Pthread_detach (pthread_self ()) = =0) {fprintf (stderr,"Tid:%lld,i have detached myself successfully.\n",(Long Long) pthread_self ()); } Else{fprintf (stderr,"\nerror:detach failed."); }      returnNULL;}intMainintargcChar*argv[]) {pthread_t tid;int*ExitCode;if(Pthread_create (&tid,null,print_thread,null) ==-1) {fprintf (stderr,"\nerror:fail to creat thread."); } fprintf (stderr,"my pid is%d.\n", Getpid ()); if(Pthread_join (tid,&exitcode)! =0) {fprintf (stderr,"Error:fail to join thread.\n"); } Else{fprintf (stderr,"Parent End successfully.\n"); }  return 0;}

[email protected]: ~$./thr
Tid:3084360592,i has detached myself successfully.
My PID is 5652.
Error:fail to join Thread.
[email protected]: ~$ (2) modify the created thread to just do the normal printing information, and the join can execute successfully. void *print_thread (void *ptr)
{fprintf (stderr, "My tid:%lld.\n", (Long Long) pthread_self ());}[email protected]: ~$./thr
My tid:3085216656.
My PID is 5702.
Parent end successfully.
[email protected]: ~$ (4) thread exit and cancel thread return a pointer to value_ptr equivalent to implicitly invoking the Pthread_exit (value_ptr) function. If the last thread of the process calls Pthread_exit, the process exits with a status return value of 0. For a thread that has been join, the return value of Vlaue_ptr is available. That is, value_ptr must point to data that is still present after the end of the thread------This problem can be solved in several ways: for example, when a thread is created to pass parameters to the thread being created, a pointer is passed in the parameter as the return value of the thread being created, so that the return value is on the stack where the thread was created In addition, the thread malloc memory is created, and the pointer is used as the return value. In addition, threads can force other threads to return through the cancellation mechanism. The thread requests the cancellation of another thread by executing pthread_cancel (), which returns without blocking when the cancellation request is made, and the actual result is determined by the type and cancellation state of the target thread (the state can be set by the function). ================================================== Overview:#include <pthread.h>int pthread_exit (void *value_ptr);int pthread_cancel (pthread_t thread);int pthread_setcancelstate (int state, int *oldstate);================================================== if the thread receives the cancel request and is in pthread_cancel_enable, it accepts the cancellation request Otherwise, if it is in a pthread_cancel_disable state, the cancellation request will be kept in a suspended state. By default, the thread is in the pthread_cancel_enable state.

This article is from the "chih, Quiet far" blog, please be sure to keep this source http://keren.blog.51cto.com/720558/176759

POSIX multithreading--Introduction to basic thread management functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.