linux--Thread Control __linux

Source: Internet
Author: User
first, the concept of the thread

threads, sometimes referred to as lightweight processes (lightweight PROCESS,LWP), are the smallest units of program execution flow. A thread is an entity in a process, the basic unit of a system that is independently dispatched and dispatched, and the thread itself does not own system resources and has only a bit of the necessary resources in operation, but it can share all the resources owned by the process with other threads of the same process.
Running multiple threads at the same time in a single program completes different tasks, called multithreading. second, the characteristics of Linux threads

1, Linux does not have a true sense of the thread, is through the process to simulate, that is, the nature of the Linux thread is the process.
2, the problem of managing threads. Each process has a management thread, and the creation, destruction, and synchronization of the process's internal threads are handled by management threads. By managing threads, the following requirements for multithreading are achieved:

The system must have the ability to kill the whole process.
The collection of line stacks must be executed after the corresponding thread has ended, so the thread cannot handle itself.
The thread that will terminate must be able to be waited, so as not to become a zombie.
The collection of thread data areas needs to be performed on all thread iterations, and this task is to manage the thread completion.
If the main thread needs to invoke Pthread_exit () and the process does not terminate, the main thread sleeps until the other thread is terminated, and the main thread is awakened by the management threads.
3, in order to maintain the thread data and memory, Linuxthreads uses the high portion of the process address space, that is, the portion below the process stack space.
4, based on the signal mechanism to achieve thread synchronization.
5, linuxthreads each thread into a process, with a unique process ID.
6. When the process receives the termination signal, the management thread is responsible for killing the other threads with this signal.
7. If an asynchronous signal is sent, the management thread passes the signal to a thread, and if the thread is currently blocking the signal, the signal is the pending state.
8, the kernel Scheduler to implement the scheduling of threads. iii. the difference between threads and processes

1, the process emphasizes resource monopoly, while thread emphasizes resource sharing;
2. There is no communication between the process and the process; the shared address space between threads and threads under the same process;
3, the thread is in the process of the address space inside the operation;
4, the process is to assume the basic unit of resource allocation, thread is the basic unit to achieve resource scheduling;
5. Thread context switching is much faster than process context switching. Four, the thread operation function

Note: because the thread functions on Linux are located in the Libpthread shared library, you should add-l pthread at compile time. For example:

Gcc-o Test Test.c-l Pthread
1. Creating Threads
#include <pthread.h>
int pthread_create (pthread_t *thread,const pthread_attr_t* attr,void* (*start routine) (void*), void *arg)

Return value: 0 returned successfully, error code returned on failure. Previously learned system functions are successfully returned 0, failure returned to 1, and the error code is stored in the global variable error, Pthread library functions are returned by return value error code, although each thread also has an error, but this is to be compatible with other function interfaces provided, The Pthread library itself does not use it, and it is clearer to return the error code by return value.

Parameters:
Thread: A pointer to the thread identifier.
Arr: Used to set the properties of a thread.
Start routine: A function pointer that starts the thread of the emerging row from the address of the start routine function.
ARG: An untyped pointer, when we need to pass arguments to the third parameter function pointer, we need to put the arguments in a struct and then pass the address of the struct as arg parameter. You can understand that the ARG parameter is the parameter of the function pointer above.
To create a thread code example:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

//new thread, print once per second, print five times
void* thread_run (void *arg)
{
    int count=0;
    while (count++<5)
    {sleep
        (1);
        printf ("%s,  %d\n", (char*) arg,count);
    }
    printf ("Thread is over...\n");
    return NULL;
}

int main ()
{
    //main thread
    printf ("pthread\n");
    pthread_t Tid;
    int Ret=pthread_create (&tid,null,thread_run, "thread is running!!!!");
    if (ret!= 0)
    {
        printf ("Pthread_creat error\n");
        return-1;
    }
    else
    {sleep
        (1);
        printf ("Pthread is running!! \ n ");
    }
    int ExitCode;
    Pthread_join (Tid, (void**) &exitcode);
    printf ("Main is over". %d\n ", exitcode);/The exit code for the new thread return
    0;
}


The above code uses a Pthread_join function, which functions to wait for the end of a thread.

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

This example lets the main thread wait for the end of the new thread. The first parameter is the thread ID of the new thread, and the second parameter is used to receive the exit code for the new thread. 2. Termination of the thread

There are three ways to terminate a thread:
Simple to return from the startup routine, the return value is the thread's exit code. The above example Thread_run function direct return is this way.

Threads can be called pthread_cancle terminated by other threads in the same process.
For example, terminating a new thread in the main thread is still the example above. The pthread_cancle parameter is the thread ID of the thread to end.
Code:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

//new thread, print once per second, print five times
void* thread_run (void *arg)
{
    int count=0;
    while (count++<5)
    {sleep
        (1);
        printf ("%s,  %d\n", (char*) arg,count);
    }
    printf ("Thread is over...\n");
    return NULL;
}

int main ()
{
    //main thread
    printf ("pthread\n");
    pthread_t Tid;
    int Ret=pthread_create (&tid,null,thread_run, "thread is running!!!!");
    if (ret!= 0)
    {
        printf ("Pthread_creat error\n");
        return-1;
    }
    else
    {sleep
        (1);
        printf ("Pthread is running!! \ n ");
    }
    Pthread_cancel (TID); End Child thread int exitcode in main thread
    ;
    Pthread_join (Tid, (void**) &exitcode);
    printf ("Main is over". %d\n ", exitcode);/new thread exit code return
    0;
}

The result should be that the main thread should print once and end directly, and the new thread exit code is-1. If a thread is called by another thread and the Pthread_cancel exception terminates, the exit code it returns will be constant pthread_canceled. This macro is defined in Pthread.h, and the value is-1.

Threads can call pthread_exit themselves to terminate themselves.
The Pthread_exit parameter is an exit code. Note that the Pthread_exit parameter or the memory unit pointed to by the new thread's return pointer must be global or malloc allocated, because when the other thread pthread_join gets the returned pointer, the newer thread function has exited.
Code:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

//new thread, print once per second, print five times
void* thread_run (void *arg)
{
    int count=0;
    while (count++<5)
    {sleep
        (1);
        printf ("%s,  %d\n", (char*) arg,count);
    }
    printf ("Thread is over...\n");
    Pthread_exit ((void*);
}

int main ()
{
    //main thread
    printf ("pthread\n");
    pthread_t Tid;
    int Ret=pthread_create (&tid,null,thread_run, "thread is running!!!!");
    if (ret!= 0)
    {
        printf ("Pthread_creat error\n");
        return-1;
    }
    else
    {sleep
        (1);
        printf ("Pthread is running!! \ n ");
    }

    int ExitCode;
    Pthread_join (Tid, (void**) &exitcode);
    printf ("Main is over". %d\n ", exitcode);/The exit code for the new thread return
    0;
}


The result is that the program executes normally, but the new thread exit code is 10. v. Detach Threads

In general, when a thread terminates, the resource is not released immediately, and its termination state remains until the other thread calls Pthread_join to obtain its state, and the system wipe releases the resources it occupies. However, a thread can also be set to a detach state, so that once the thread is terminated, it immediately reclaims all the resources it occupies and does not retain the termination state, when the main thread does not have to block the wait and can do other work. Pthread_join cannot be called 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 detach thread can place the thread in detach state, that is, you cannot call two pthread_join on the same thread, or if you have already invoked a pthread on a thread _detach can no longer invoke pthread_join.

Threads are separable (detached) or associative (joinable), a binding thread that can be retrieved by other threads and killed. His memory resource (eg: stack) is not released until it is recycled by another thread. In contrast, a detached thread cannot be recycled or killed by another thread, and its memory resources are automatically released by the system when it terminates.
By default, threads are created to be combined. To avoid memory leaks, each pthread_join thread should be displayed as a collection, that is, invoke the call. If not join, it will cause resources, memory leakage.

Because after calling Pthread_join, if the new thread that should be join does not run, the caller will be blocked, and we sometimes don't want to. Code Pthread_detach (Pthread_self ()) or the main thread call Pthread_detach (THREAD_ID) can be added to the new thread to set the new thread to separable, so that all resources are automatically freed when the new thread is run.

Code:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

//new thread, print once per second, print five times
void* thread_run (void *arg)
{

    Pthread_detach (pthread_self ());
    printf ("%s\n", (char*) arg);
    return NULL;
}

int main ()
{
    //main thread
    printf ("pthread\n");
    pthread_t Tid;
    int Ret=pthread_create (&tid,null,thread_run, "Thread is running!!");
    if (ret!= 0)
    {
        printf ("Pthread_creat error\n");
        return-1;
    }

    Wait
    int ret1=0;
    Sleep (1);
    if (0== pthread_join (tid,null))
    {
        printf ("Pthread wait success!\n");
        Ret1 = 0;
    }
    else
    {
        printf ("Pthread wait failed!\n");
        Ret1 = 1;
    }
    return ret1;
}

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.