Thread and line programming

Source: Internet
Author: User

Original link: http://www.orlion.ga/1250/

One, thread

Multiple threads of the same process share the same address space, so the Text Segment, Data Segment are shared, and if you define a function that can be called in a thread, if you define a global variable that can be accessed in each thread, in addition, Threads also share the process resources and environment:

      • File descriptor

      • How each signal is processed (sig_ign, SIG_DFL, or a custom signal processing function)

      • Current working directory

      • User ID and Group ID

But some resources make each thread have one copy:

      • Thread ID

      • Context, including values for various registers, program counters, and stack pointers

      • Stack space

      • errno variable

      • Signal Shielding Word

      • Scheduling priority

Second, the Line program control system

1. Creating Threads

#include <pthread.h>int pthread_create (pthread_t *restrict thread, const pthread_attr_t * Restrict attr, void * (*st Art_routine) (void *), void * restrict Arg);

Return value: Successful return 0, Failure returns error number. Other system functions return 0 successfully, the failure returns 1, and the error number is stored in the global variable errno, and the function of the Pthread library returns the error number through the return value, although each thread also has a errno, which is provided for compatibility with other function interfaces. The Pthread library itself does not use it and returns the error code with a clearer return value.

     call Pthread_create () in a thread, the current thread returns from Pthread_create () to continue execution after the thread is created. The code that the new thread executes is determined by the function pointer we passed to Pthread_create Start_routine . The Start_routine function receives a parameter that is passed to it by the ARG parameter of the ptherad_create, the type of which is void *, which is interpreted by what type of pointer is defined by the caller itself. The return value type of start_routine is also void *, and the meaning of this pointer is also defined by the caller itself. When Start_routine returns, the thread exits, and other threads can call Pthread_join to get the return value of Start_routine, similar to the parent process calling wait () to get the child process's exit status.

    pthread_create successfully returns, the ID of the newly created thread is filled in to the memory unit pointed to by the thread parameter. The type of process ID is pid_t, and the ID of each process is unique across the system, and calling Getpid () can get the ID of the current process and is a positive integer value. The type of thread ID is thread_t, it is only guaranteed to be unique in the current process, thread_t this type has different implementations in different systems, he may be an integer value, or it may be a struct or an address, so it cannot simply be used as an integer to print with printf, calling pthread_self () can obtain the ID of the current thread.

    attr parameter represents a thread property. Example:

#include  <stdio.h> #include  <string.h> #include  <stdlib.h> #include  < pthread.h> #include  <unistd.h>pthread_t ntid;void printids (const char *s) {         pid_t      pid;         pthread_t  tid;         Pid = getpid ();         tid = pthread_self ();         printf ("%s pid %u tid %u  (0x%x) \ n",  s,   (Unsigned int) pid,                 (Unsigned int) tid,  (Unsigned int) tid);} VOID&NBSP;*THR_FN (Void *arg) {        printids (ARG);         return null;} Int main (VoiD) {        int err;         err = pthread_create (&ntid, NULL, thr_fn,  "new thread: ");         if  (err != 0)  {                 fprintf (stderr,  "Can ' t create  thread: %s\n ",  strerror (err));                 exit (1);        }         printids ("Main thread:");         sleep (1);         return 0;}

Compile (gcc compile with option-lpthread) to run the result:

On Linux, the thread_t type is an address value, and multiple threads that belong to the same process call Getpid () to get the same process number, and the call Pthread_self () gets a different thread number

Because the Pthread_create error code is not errno, so you cannot print the error message directly with the Perror (), you can first use strerror () to turn the error code into an error message and then print

If any thread calls exit or _exit, all threads of the entire process are terminated, and since return from the main function is equivalent to calling exit, in order to prevent the newly created thread from terminating without execution, we delay 1 seconds before the main function return. But even if the main thread waits 1 seconds, the kernel does not necessarily dispatch the newly created thread execution.

2. Terminating Threads

There are three ways to terminate a thread without terminating a process

      • Return from the thread function. The main thread return is equivalent to calling exit.

      • One thread can invoke Pthread_cancel to terminate another thread in the same process

      • Threads can invoke pthread_exit to terminate themselves.

It is more complicated to use Pthread_cancel to terminate a thread in both synchronous and asynchronous situations.

#include <pthread.h>void pthread_exit (void *value_ptr);

Value_ptr is a void * type, and the use of a thread function return value is the same as other threads can call Pthread_join to get this pointer.

The memory cell that the Pthread_exit or return pointer points to must be global or allocated with malloc and cannot be allocated on the stack of the thread function, because when the other thread gets the return pointer, the function has exited.

#include <pthread.h>int pthread_join (pthread_t thread, void **value_ptr);

Return value: Successful return 0, failure return error number

The thread that called the function suspends the wait until a thread with the ID of thread terminates. Thread threads A different method terminates, the terminating state obtained through Pthread_join is different, summarized as follows:

        • If the thread thread returns by return, Value_ptr points to a cell that contains the return value of the thread's function.

        • If the thread thread is called by another thread, the pthread_cancel exception terminates, and value_ptr points to the cell where the constant pthread_canceled is stored.

        • If thread threads are terminated by their own invocation of Pthread_exit, value_ptr points to the cell that holds the arguments passed to Pthread_exit.

If you are not interested in the terminating state of thread threads, you can pass NULL to the VALUE_PTR parameter.

Cases:

#include  <stdio.h> #include  <stdlib.h> #include  <pthread.h> #include  < UNISTD.H&GT;VOID&NBSP;*THR_FN1 (Void *arg) {        printf ("thread  1 returning\n ");        return  (void *) 1;} VOID&NBSP;*THR_FN2 (Void *arg) {        printf ("thread 2  Exiting\n ");         pthread_exit ((void *) 2);} Void *thr_fn3 (Void *arg) {        while (1)  {                 printf ("Thread 3  writing\n ");                 sleep (1);         }}int main (void) {         pthread_t   tid;        void        * Tret;        pthread_create (&tid, NULL, thr_fn1,  NULL);         pthread_join (Tid, &tret);         printf ("thread 1 exit code %d\n",  (int) tret);         pthread_create (&tid, null, thr_fn2, null);         pthread_join (Tid, &tret);         printf ("thread 2 exit code %d\n",  (int) tret);         pthread_create (&tid, null, thr_fn3, null);         sleep (3);         pthread_cancel (TID);          pthread_join (Tid, &tret);         printf ("Thread  3 exit code %d\n ",  (int) tret);         return  0;}

Results:

The value of the constant pthread_canceled in the Linux pthread Library is-1. You can find its definition in the header file Pthread.h:

#define PTHREAD_CANCELED ((void *)-1)
    • In general, after the process terminates, its terminating state is retained until the other thread calls Pthread_join to get its state. But the thread can also be set to the detach state, so that once the thread terminates, it reclaims all the resources it occupies without leaving the terminating state. You cannot call Pthread_join on a thread that is already in the detach state, and such a call will return EINVAL. Calling Pthread_join or Pthread_detach on a thread that has not yet been detach can set the thread to the detach state, that is, you cannot call two pthread_join on the same thread, or if you have already called Pthread_ on a thread Detach can no longer call pthread_join.
#include <pthread.h>int pthread_detach (pthread_t tid);
    • Return value: Successful return 0, Failure returns error number.

Thread and line programming

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.